Two 'main' functions in C/C++
Can I write a program in C or in C++ with two main functions?
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.
Yes; however, it's platform specific instead of standard C, and if you ask about what you really want to achieve (instead of this attempted solution to that problem), then you'll likely receive answers which are more helpful for you.
No, a program can have just 1 entry point(which is main()
). In fact, more generally, you can only have one function of a given name in C.
If one is static
and resides in a different source file I don't see any problem.