Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 $@ $^
like image 352
blue Avatar asked Oct 21 '22 12:10

blue


1 Answers

Some times the link order can be important, try -lO -lABC

like image 114
epatel Avatar answered Oct 28 '22 21:10

epatel