简体   繁体   中英

Stop shared library linking dropping unused classes

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.

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 .

What the solution I arrived at was as follows. Before I had:

BaseView
 +-- virtual void foo() = 0;
 +- Base2DView
     +-- virtual void foo() {...}
     +- Concrete2DView
         +-- virtual void foo() {...}
         +- Specialised2DView
             +-- void bar() {foo();}

If I changed the leaf call to:

             +-- void bar() {Concrete2DView::foo();}

The code linked and ran problem-free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM