Reputation: 149404
I want to use some functions from a .cpp source file that has a main function in my .cpp source file. (I'm building with make and gcc.)
Here's the rule from my Makefile:
$(CXX) $(CXXFLAGS) $(INCLUDES) $(SRCS) $(LIBS) -o $@
And here's the output (with some names changed to prevent distraction):
$ make foo
g++ -g -Wall -m32 -Ilinux/include foo.cpp bar.cpp -o foo
/tmp/ccJvCgT3.o: In function `main':
/home/dspitzer/stuff/bar.cpp:758: multiple definition of `main'
/tmp/ccUBab2r.o:/home/dspitzer/stuff/foo.cpp:68: first defined here
collect2: ld returned 1 exit status
make: *** [foo] Error 1
How do I indicate to gcc that I want to use the main from foo.cpp?
Update: I should have added that "bar.cpp" is "someone else's" code, and has it's own reason for a main. (It sounds like I should work with that someone else to have him split the shared functions into a separate file.)
Upvotes: 2
Views: 223
Reputation: 98984
It sounds like I should work with that someone else to have him split the shared functions into a separate file
Exactly, thats the best option. If you both need seperate main
s for testing, different products or other reasons, factor the commonly used code and the main
s out in seperate files and only use the one you need according to some build setting.
Upvotes: 1
Reputation: 76579
The simplest would be to delete the second main(...){ ...}, and keep the rest of the functions. This solves the problem easily
Upvotes: 1
Reputation: 300865
what you could do is wrap each main() function in an #ifdef
block, then use the command line to define the symbol which will cause the relevant main to be used.
#ifdef USE_MAIN1
int main(void)
{
}
#endif
Then ensure the gcc command line gets something like this added to it
-DUSE_MAIN1
Or just restructure your code!
Upvotes: 5
Reputation: 503963
It's not about which main
to use as your "main", because you won't even get that far.
You can't have redefinitions of functions, it breaks the One Definition Rule. In the same way you can't do:
void foo(void)
{
// number one
}
void foo(void)
{
// number two
}
// two foo's? ill-formed.
You can't try to compile multiple main
's. You'll need to delete the other ones.
Upvotes: 2