views:

85

answers:

4

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.)

+2  A: 

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.

GMan
+4  A: 

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!

Paul Dixon
If he can modify the code to put in a compiler macro, then he can modify the code to split off the functions he wants into a separate file and let the linker do its job. That way he doesn't clutter his own code base with an unwanted `main` or pollute the other guy's code with a meaningless `#ifndef`.
Beta
The answer was written before the OP indicated modifications were not possible. I agree it's not ideal, but it answered the question of how to compile and link two files which define the same function.
Paul Dixon
I'm going to accept this answer because it allows me to solve the problem "quick and dirty" now before working with the other engineer later to solve it correctly.
Daryl Spitzer
+1  A: 

The simplest would be to delete the second main(...){ ...}, and keep the rest of the functions. This solves the problem easily

rubenvb
+1  A: 

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 mains for testing, different products or other reasons, factor the commonly used code and the mains out in seperate files and only use the one you need according to some build setting.

Georg Fritzsche