Search code examples
c++gcclinkerprogram-entry-pointmultiple-definition-error

How do I link in functions from a .cpp source file that also has a 'main'?


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


Solution

  • 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!