Multiple Main () Method

Jul 14, 2011 at 3:07am
Hi.

I want to ask can we have multiple main() method in one project. Because I want to create multiple main() method for different projects in 1 solution. Because right now, everytime I want to create new main() method, I must create it inside different solution coz there'll be error...

thanks...^^
Jul 14, 2011 at 3:15am
No, you can't have two main methods, but you can use the preprocessor to help you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define USING_MAIN_1
#include <iostream>
using namespace std;

#ifdef USING_MAIN_1
int main() //main 1
{
     cout<<"This is main 1!"<<endl;
     return 0;
}
#else
int main() //main 2
{
     cout<<"This is main 2!"<<endl;
     return 0;
}
#endif 

With the above example, you can comment out #define USING_MAIN_1 to have the your project use main 2.
Jul 14, 2011 at 3:25am
So, it means that you can't run both of the main () methods at the same time? But still you can have more that 1 method inside one .cpp file?
Jul 14, 2011 at 3:31am
Both main methods are in the .cpp file, BUT with the above example, the preprocessor takes one out and the compiler only sees the other.

You could do it this way, too

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() //main 1
{
     cout<<"This is main 1!"<<endl;
     return 0;
}

/*int main() //main 2
{
     cout<<"This is main 2!"<<endl;
     return 0;
}*/

With this method, to use main 2 you would uncomment it and comment out main 1. The method in my previous post is similar to this except the "commenting out one and uncommenting the other" is done for you automatically by the preprocessor.
Jul 14, 2011 at 3:34am
It means that only 1 main() method can run? Sorry. I'm a bit confused. Still new to this.@.@
Jul 14, 2011 at 3:41am
If the compiler sees more than one main() method, your program won't compile. So, yes you can have only one int main{...} in your program and thus only one "main" can run.

Using my last post as an example, if you compile and run it, it will show "This is main 1!", meaning that main 1 was run.

If on the other hand, you want main 2 to run, you would comment out main 1 and uncomment main 2. You would need to compile and run it again. This time it will show "This is main 2!", showing that the second main is running. You need one commented because the compiler would complain that there are two mains.
Jul 14, 2011 at 3:43am
Oh, I see. I get it now. Thanks a lot for the help...^^
Topic archived. No new replies allowed.