如何强制 gcc 链接未使用的静态库

How to force gcc to link an unused static library(如何强制 gcc 链接未使用的静态库)
本文介绍了如何强制 gcc 链接未使用的静态库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个程序和一个静态库:

I have a program and a static library:

// main.cpp
int main() {}

// mylib.cpp
#include <iostream>
struct S {
    S() { std::cout << "Hello World
";}
};
S s;

我想将静态库(libmylib.a)链接到程序对象(main.o),虽然后者不使用前者的任何符号直接.

I want to link the static library (libmylib.a) to the program object (main.o), although the latter does not use any symbol of the former directly.

以下命令似乎不适用于 g++ 4.7.它们将在没有任何错误或警告的情况下运行,但显然 libmylib.a 不会被链接:

The following commands do not seem to the job with g++ 4.7. They will run without any errors or warnings, but apparently libmylib.a will not be linked:

g++ -o program main.o -Wl,--no-as-needed /path/to/libmylib.a

g++ -o program main.o -L/path/to/ -Wl,--no-as-needed -lmylib

你有更好的想法吗?

推荐答案

使用 --whole-archive 链接器选项.

在命令行中之后的库不会丢弃未引用的符号.您可以通过在这些库之后添加 --no-whole-archive 来恢复正常的链接行为.

Libraries that come after it in the command line will not have unreferenced symbols discarded. You can resume normal linking behaviour by adding --no-whole-archive after these libraries.

在您的示例中,命令将是:

In your example, the command will be:

g++ -o program main.o -Wl,--whole-archive /path/to/libmylib.a

一般来说,它将是:

g++ -o program main.o 
    -Wl,--whole-archive -lmylib 
    -Wl,--no-whole-archive -llib1 -llib2

这篇关于如何强制 gcc 链接未使用的静态库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)