Can I write a program in C or in C++ with two main functions?
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.
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.
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.
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:
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.
Create a library out of the shared code and compile each main file against that library. You'll end up with two executables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With