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

I am having this problem when the GCC compiler seems to fail when it comes to linking the two object files that I have. Both object files foo1.cc and foo2.cc include classes from the header file named foo1.hh In addition, the header file foo.hh has an instance of the object that appears in foo1.cc as an external declaration.

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

When I compile the source files with the following command, everything works:

 g++ foo1.cc foo2.cc 

The above command will create an executable file called a.out .

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

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

The GCC compiler complains that there are undefined function references in foo2.cc These functions must be defined in foo1.cc ; however, the linker does not recognize this.

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

+7
source share
2 answers

No problem, you have an error in the gcc syntax.

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

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

+8
source

Your last command, which is the bind command, says: create an executable from foo2.o and name the executable foo1.o. The compiler, most likely, will not find all the necessary information to create the executable file, since you intend to use both foo1.o and foo2.o. Just leave the -o flag in general:

 g++ foo1.o foo2.o 
+3
source

All Articles