How to compile and link together object files in C++ using the same header file?
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
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, 2022Comments
-
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
andfoo2.cc
include classes from a header file calledfoo1.hh
. In addition, the header filefoo.hh
has as an external declaration of an object instance that appears infoo1.cc
.It should be noted that the header file
foo.hh
will only be defined once between the two source filesfoo1.cc
andfoo2.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 infoo1.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.