[英]How to compile and link together object files in C++ using the same header file?
I'm having this issue where the GCC compiler seems to be failing when it comes to linking two object files I have together. 我遇到这个问题,GCC编译器在链接我在一起的两个目标文件时似乎失败了。 Both object files
foo1.cc
and foo2.cc
include classes from a header file called foo1.hh
. 目标文件
foo1.cc
和foo2.cc
包含来自名为foo1.hh
的头文件中的foo1.hh
。 In addition, the header file foo.hh
has as an external declaration of an object instance that appears in foo1.cc
. 此外,头文件
foo.hh
具有出现在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
. 应该注意的是,头文件
foo.hh
将仅在两个源文件foo1.cc
和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
. 上面的命令将生成一个名为
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
. GCC编译器抱怨
foo2.cc
中有对函数的未定义引用。 These functions should be defined in foo1.cc
; 这些函数应该在
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. 我想知道是否有办法解决GCC编译器的这个问题。
There is no issue, you've got an error in your gcc syntax. 没有问题,你的gcc语法中有错误。
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. -o
参数接受输出文件的名称,因此在您的情况下,它将使用链接结果覆盖foo1.o。
Your last command which is the linking command is saying: create an executable out of foo2.o and name the executable foo1.o. 你的最后一个命令就是链接命令:用foo2.o创建一个可执行文件并命名可执行文件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.
链接器可能找不到创建可执行文件所需的所有信息,因为您打算同时使用foo1.o和foo2.o. Just leave out the
-o
flag altogether: 完全省略
-o
标志:
g++ foo1.o foo2.o
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.