How to compile and link together object files in C++ using the same header file?

17,204

Solution 1

There is no issue, you've got an error in your gcc syntax.

g++ -c foo1.cc
g++ -c foo2.cc
g++ -o foo foo1.o foo2.o

the -o parameter accepts name of the output file, so in your case, it would overwrite foo1.o with result of linkage.

Solution 2

Your last command which is the linking command is saying: create an executable out of foo2.o and name the executable foo1.o. The linker will likely not find all the information it needs to create the executable, since your intention was to use both foo1.o and foo2.o. Just leave out the -o flag altogether:

g++ foo1.o foo2.o
Share:
17,204
Justin
Author by

Justin

Hi. My name is Justin. I recently graduated from the University of Waterloo in Waterloo, ON, Canada with a Bachelor of Applied Science in Computer Engineering. I aspire to continue developing my skills in software and embedded systems development.

Updated on June 19, 2022

Comments

  • Justin
    Justin almost 2 years

    I'm having this issue where the GCC compiler seems to be failing when it comes to linking two object files I have together. Both object files foo1.cc and foo2.cc include classes from a header file called foo1.hh. In addition, the header file foo.hh has as an external declaration of an object instance that appears in foo1.cc.

    It should be noted that the header file foo.hh will only be defined once between the two source files foo1.cc and foo2.cc.

    When I compile the source files using the following command, everything seems to work:

    g++ foo1.cc foo2.cc
    

    The above command will produce an executable called a.out.

    When I try to compile the source files into object files independently:

    g++ -c foo1.cc
    g++ -c foo2.cc
    g++ -o foo1.o foo2.o
    

    The GCC compiler complains that there are undefined references to functions in foo2.cc. These functions should be defined in foo1.cc; however, the linker doesn't recognize that.

    I was wondering if there was a way to get around this issue with the GCC compiler.