Strange undefined link when linking

I reproduced the behavior that I experienced in a larger project in the next few lines of code. I refused guards #ifndefand directives #includein an attempt to improve readability. Linker error occurs on invocation make. The makefile is included at the end of the question.

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

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 is the source code. I tried to make it so small and as readable as possible. Any idea what the problem is?

/***** 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);
}

The main thing here:

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

And here is 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 $@ $^
+5
source share
1 answer

Sometimes link ordering may be important, try -lO -lABC

+3
source

All Articles