[英]Linking with g++ undefined reference
I've written the following code: 我编写了以下代码:
//--a.cpp--//
#include <stdio.h>
class A
{
public:
void bar();
virtual void foo()=0;
};
class B: public A
{
public:
void foo()
{
A::bar();
}
}
int main()
{
B *b= new B();
b->foo();
return 0;
}
//--b.cpp--//
#include <stdio.h>
class A
{
public:
void bar()
{
printf("class A");
}
}
Now I'm comipilng and linking this modules as follow: 现在,我按照以下步骤进行comipilng和链接该模块:
g++ -c a.cpp
g++ -c b.cpp
g++ -o bin a.o b.o
But the undefined reference error
is raised by linker. 但是链接器会引发
undefined reference error
。 I don't understand, why? 我不明白,为什么?
You have not defined A::bar()
in a.cpp
. 您尚未在
a.cpp
定义A::bar()
。 In B::foo()
that method is called, but it does not have an implementation. 在
B::foo()
,该方法被调用,但是它没有实现。 So linker cannot link it. 因此,链接器无法链接它。
In b.cpp
you created another class name A
, but it is unrelated to the first one. 在
b.cpp
您创建了另一个类名A
,但它与第一个类名无关。 It will not create any problem here, but you will get Redefinition Error if you include any one file into another or both files in a third file (although including .cpp is uncommon). 它不会在此处造成任何问题,但是如果将任何一个文件包含到另一个文件中,或者将两个文件都包含在第三个文件中,则将出现“ 重新定义错误” (尽管很少包含.cpp )。 There must be only one definition of a name in one Translation Unit .
一个翻译单位中只能有一个名称的定义。
Common practice is to declare class in header file (.hXX) and implement the methods in source file (.cXX) . 通常的做法是在头文件(.hXX)中声明类,并在源文件(.cXX)中实现方法。 If you want methods to be
inline
d then you may define in header or explicitly declare the method as inline . 如果您希望方法是
inline
d,则可以在header中定义或将方法显式声明为inline 。 See Translation Unit , ODR . 参见ODR 翻译部 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.