Issue
I've found lots of questions on the opposite question of eliminating dead code, but I cannot find an answer to this:
Given a class hierarchy like:
BaseView
+- Base2DView
+- Concrete2DView
+- Specialised2DView
I link all the files together into view_classes.a
, then I add in code that instantiates Concrete2DView
and make a view_renderer.so
. Next, I create another library specialised_view_renderer.so
that instantiates Specialised2DView
and lists view_renderer.so
as a dependency.
However, the process of generating view_renderer.so
has eliminated the Specialised2DView.cpp.o
file as unused code, as nothing turns up when I use nm view_renderer.so
.
I know that either linking against view_classes.a
or moving Specialised2DView.cpp
to the specialised_view_renderer.so
project would fix this, but this is legacy third-party code that I probably shouldn't fiddle with too much.
So, is there an easy way to mark Specialised2DView.cpp.o
or the class within as not to be eliminated when building the view_renderer.so
? Bonus points if there is an option for a standard cmake
target_link_libraries()
line.
Solution
So, is there an easy way to mark Specialised2DView.cpp.o or the class within as not to be eliminated when building the view_renderer.so?
Yes:
g++ -shared -o view_renderer.so ... \
-Wl,--whole-archive view_classes.a -Wl,--no-whole-archive
To understand why this is happening, and why the solution works, you need to know the rules which linkers use to select which objects to include in the link. A good description is here.
Answered By - Employed Russian