简体   繁体   中英

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:

g++ -c a.cpp
g++ -c b.cpp
g++ -o bin a.o b.o

But the undefined reference error is raised by linker. I don't understand, why?

You have not defined A::bar() in a.cpp . In B::foo() that method is called, but it does not have an implementation. So linker cannot link it.

In b.cpp you created another class name A , but it is unrelated to the first one. 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). 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) . If you want methods to be inline d then you may define in header or explicitly declare the method as inline . See Translation Unit , ODR .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM