问题描述
我有一个程序和静态库:
I have a program and a static library:
// main.cpp
int main() {}
// mylib.cpp
#include <iostream>
struct S {
S() { std::cout << "Hello World\n";}
};
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
你有什么更好的想法?
Do you have any better ideas?
推荐答案
使用 - 全归档
链接器选项
库,来的之后的它在命令行中不会有丢弃未引用的符号。您可以通过添加恢复正常链接行为 - 无全归档
这些库后
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
在一般情况下,这将是:
In general, it will be:
g++ -o program main.o \
-Wl,--whole-archive -lmylib \
-Wl,--no-whole-archive -llib1 -llib2
这篇关于如何强制GCC链接未使用的静态库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!