Linux 如何强制 gcc 链接库中未引用的静态 C++ 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4767925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:35:48  来源:igfitidea点击:

How to force gcc to link unreferenced, static C++ objects from a library

c++linuxgccstatic-linkingstatic-initialization

提问by Gene Vincent

I'm using a C++ library that can be built as either a shared or a static library. This library uses a factory technique, where static objects register themselves when the program starts and the static objects get created.

我使用的 C++ 库可以构建为共享库或静态库。该库使用工厂技术,其中静态对象在程序启动并创建静态对象时注册自己。

This works fine as long as the shared library is used. When the static version is used, none of the static objects get included into the final program (because they aren't referenced directly) and thus their functionality isn't available.

只要使用共享库,这就可以正常工作。使用静态版本时,没有任何静态对象包含在最终程序中(因为它们没有被直接引用),因此它们的功能不可用。

Is there a way to force gcc to include all static objects from a library when linking?

有没有办法强制 gcc 在链接时包含库中的所有静态对象?

The library is Open Source and I could modify it, if that helps.

该库是开源的,如果有帮助,我可以对其进行修改。

采纳答案by nos

You can use -Wl,--whole-archive -lyourlib, see the manpage for ldfor more info.

您可以使用-Wl,--whole-archive -lyourlibld有关详细信息,请参阅联机帮助页。

Any static libraries mentioned after -Wl,--whole-archive on the command line gets fully included, you can turn this off again too if you need to , as in e.g. -Wl,--whole-archive -lyourlib -Wl,--no-whole-archive -lotherlib

在命令行上 -Wl,--whole-archive 之后提到的任何静态库都被完全包含,如果需要,您也可以再次关闭它,例如 -Wl,--whole-archive -lyourlib -Wl,--no-whole-archive -lotherlib

回答by PA314159

Use:

用:

g++ -u <SYMBOL_NAME> ...

Note that -uis lowercase

注意-u是小写