Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two main functions

Tags:

c++

main

Can we have two main() functions in a C++ program?

like image 390
Prasoon Saurav Avatar asked Apr 13 '10 02:04

Prasoon Saurav


People also ask

Can there be 2 main functions?

No, you cannot have more than one main() function in C language. In standard C language, the main() function is a special function that is defined as the entry point of the program.

Can there be 2 main functions in C?

it's not possible in c to have more than 1 main-function. you could use preprocessor directives like "#ifdef" to compile just one main-function at the time.

What is main function?

The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.


3 Answers

The standard explicitly says in 3.6.1:

A program shall contain a global function called main, which is the designated start of the program. [...] This function shall not be overloaded.

So there can one only be one one main function in the global scope in a program. Functions in other scopes that are also called main are not affected by this, there can be any number of them.

like image 156
sth Avatar answered Oct 26 '22 08:10

sth


Only one function can be named main outside of any namespace, just as for any other name. If you have namespaces foo and bar (etc) you can perfectly well have functions named foo::main, bar::main, and so on, but they won't be treated as anything special from the system's point of view (only the function named main outside of any namespace is treated specially, as the program's entry point). Of course, from your main you could perfectly well call the various foo::main, bar::main, and so on.

like image 39
Alex Martelli Avatar answered Oct 26 '22 08:10

Alex Martelli


Yes! Why not?

Consider the following code:

 namespace ps
 {
     int main(){return 0;}
 }

 int main()
 {
     ps::main();
 }

Its ::main() that will be called during execution.

like image 43
Prasoon Saurav Avatar answered Oct 26 '22 07:10

Prasoon Saurav