Search code examples
c++static-linkingvtable

virtual functions in static libraries


When I have an abstract base class foo, defined in libX.a

class foo {
    virtual void bar() = 0;
};

... and a derived class foo_impl, defined in libY.a

class foo_impl : public foo {
    void bar() { /* do something */ }
};

... and use both libraries to link a program -lX -lY

int main() {
    foo* my_foo = receive_a_foo_from_somewhere();
    my_foo->bar();
}

Then

  • how can I force the linker to actually link the symbol referring to foo_impl::bar()?
  • does objdump -t program list foo_impl::bar() when it is correctly linked?

EDIT: to clarify, I am using linux with gcc or clang

EDIT 2: had missed virtual for bar()

EDIT 4: I apologize for missing clarity. The question should have been "how can I force the linker to actually include foo_impl::bar() in the executable so it can be resolved at runtime?"


Solution

  • It appears there are at least two ways to get the linker to include foo_impl::bar() functionality in the executable:

    1. With gcc, one can use -Wl,--whole-archive to link an entire static library - no matter what.
    2. As Captain Obvlious pointed out, when foo_impl is used in the program, it's virtual functions are tagged as having been used and are thus included in the executable. This could also be an otherwise useless static dummy foo_impl object.