Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

object

gcc

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.

like image 915
Justin Avatar asked Jun 04 '12 15:06

Justin


2 Answers

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.

like image 58
nothrow Avatar answered Sep 22 '22 23:09

nothrow


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
like image 22
jxh Avatar answered Sep 26 '22 23:09

jxh