Question

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?"

Était-ce utile?

La solution 2

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.

Autres conseils

Since the bar method is defined as virtual, there is no need of static linking. The linking will be done dynamically at runtime based on the object type to which the *my_foo refers to. Regardless of whether it's defined in libX.a or libY.a.

Answer to you question how to force the linker to link the symbol referring to foo_impl::bar()?

You can't force the linker to link to particular implementation. The linking will happen based on which object address you got from receive_a_foo_from_somewhere().

Obviously the implementation should be linked to your exe. If it is not available it will definitely fail. But you can't force linker to link particular implementation,

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top