简体   繁体   中英

weird undefined reference while linking

I reproduced the behaviour I experienced in a bigger project in the following few lines of code. I left out the #ifndef guards and the #include directives in an attempt to improve readability. The linker error is produced when invoking make . The makefile is included at the end of the question.

Class C inherits from B which inherits from A. O is a totally different class.

The linker complains:

g++ -o main main.cpp -L. -lABC -lO
./libO.a(O.o): In function `O::foo(A)':
O.cpp:(.text+0x1f): undefined reference to `C::C(A const&)'

Here's the source code. I tried to make it as small and as readable as possible. Any idea what's the problem?

/***** A.h *****/
class A
{
    public:
    A();
    A(const A& a);
};

/***** A.cpp *****/
A::A() {}
A::A(const A& a) {}

/****** BC.h *******/
class B : public A
{
    public:
    B(const A& a);
};

class C :  public B 
{
    public:
    C(const A& a);
};

/******* BC.cpp ********/
B::B(const A& a) : A(a) {}
C::C(const A& a) : B(a) {}

/***** O.h *****/
class O
{
    public:
    void foo(A a);
};

/***** O.cpp *****/
void O::foo(A a)
{
    C c(a);
}

Here's the main:

/******* main.cpp *******/
int main()
{
    A a;
    O o;
    o.foo(a);
    return 0;
}

And here's the makefile:

%.o: %.cpp %.h
    g++ -c $<

.PHONY: all
all: mklibs main

main: main.cpp
    g++ -o $@ main.cpp -L. -lABC -lO

mklibs: libABC.a libO.a

libABC.a: A.o BC.o
    ar -r $@ $^

libO.a: O.o
    ar -r $@ $^

有时链接顺序很重要,请尝试-lO -lABC

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