Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two 'main' functions in C/C++

Tags:

c++

c

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

like image 632
kuppusamy Avatar asked Jan 02 '10 08:01

kuppusamy


People also ask

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.

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 you have two main functions in C++?

Every C/C++ program has at least one function that the name is main. The main function is called by the operating system by which our code is executed. We can make n number of function in a single program but we can make only one main function in a single program.


2 Answers

No. All programs have a single main(), that's how the compiler and linker generate an executable that start somewhere sensible.

You basically have two options:

  1. Have the main() interpret some command line arguments to decide what actual main to call. The drawback is that you are going to have an executable with both programs.

  2. Create a library out of the shared code and compile each main file against that library. You'll end up with two executables.

like image 152
Uri Avatar answered Oct 02 '22 13:10

Uri


You can have two functions called main. The name is not special in any way and it's not reserved. What's special is the function, and it happens to have that name. The function is global. So if you write a main function in some other namespace, you will have a second main function.

namespace kuppusamy {   int main() { return 0; }  }  int main() { kuppusamy::main(); } 

The first main function is not special - notice how you have to return explicitly.

like image 38
Johannes Schaub - litb Avatar answered Oct 02 '22 12:10

Johannes Schaub - litb