Two 'main' functions in C/C++

后端 未结 16 1421
一整个雨季
一整个雨季 2020-12-01 16:08

Can I write a program in C or in C++ with two main functions?

相关标签:
16条回答
  • 2020-12-01 16:35

    You can write it, and it'll compile, but it won't link (unless your linker is non-comformant)

    0 讨论(0)
  • 2020-12-01 16:35

    Not in C, C++

    but now C#.net introduce trick you can use 2 mains in one application. i implemented in my application too. I have scenario and requirement and implemented it successfully.

    reference and proof is here https://www.youtube.com/watch?v=KJcBj3hLIpM

    0 讨论(0)
  • 2020-12-01 16:43

    If one is static and resides in a different source file I don't see any problem.

    0 讨论(0)
  • 2020-12-01 16:43

    In some very special architecture, you can. This is the case of the Cell Processor where you have a main program for the main processor (64-bit PowerPC Processors Element called PPE) and one or many main program for the 8 different co-processor (32-bit Synergistic Processing Element called SPE).

    0 讨论(0)
  • 2020-12-01 16:44

    Yes , Multiple main() are allowed but not in global namespace.

    "Every C++ program must have exactly one global function named main()" - Bjarne stroustrup.

    Eg 1 :

    namespace foo
    {
      int main() //Main 1 
      {
        return 1;
      }
    }
    
    int main() // Main 2   
    {
    
    }
    
    // Main 1 : namespace is foo
    
    // Main 2 : namespace is global
    
    // Allowed : Yes , its allowed as both the main() are present in different namespaces.
    

    Eg 2 :

    int main() //Main 1 
    {
        return 1;
    }
    
    void main() // Main 2   
    {
    
    }
    
    // Main 1 : namespace is global
    
    // Main 2 : namespace is global
    
    // Allowed : No , as multiple main() in global namespace . Compile-time error is thrown : redefinition of main() .. 
    
    0 讨论(0)
  • 2020-12-01 16:49

    No,The main() is the entry point to your program,since u can't have two entry points you cant have two main().

    0 讨论(0)
提交回复
热议问题