Two 'main' functions in C/C++

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

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

16条回答
  •  挽巷
    挽巷 (楼主)
    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() .. 
    

提交回复
热议问题