weird undefined reference while linking

c++, inheritance, linker-errors

Solution

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

Problem

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 $@ $^ ```

Original source