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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With