使用GNU工具链(gcc/ld)从静态库创建共享库
我无法从静态库生成共享库.虽然我知道还有其他选择,但现在我不满意(而不是卡住)为什么不起作用以及如何使其起作用.
I am having trouble generating a shared object from a static library. While I know there are other alternatives, I am now bothered (as opposed to stuck) by why this isn't working and how to make it work.
下面是我正在使用的非常简单的源代码.
Below is very simple source code I am using.
get_zero.c
get_zero.c
#include "get_zero.h"
int
get_zero(void)
{
return 0;
}
get_zero.h
get_zero.h
int get_zero(void);
main.c
#include <stdio.h>
#include <string.h>
#include "get_zero.h"
int
main(void)
{
return get_zero();
}
目标是使用libget_zero_static和libget_zero_shared创建两个功能相同的应用程序.
The goal is create two functionally equal applications using libget_zero_static and libget_zero_shared.
这是我的编译/链接步骤:
Here are my compilation/linking steps:
gcc -c -fPIC get_zero.c
ar cr libget_zero_static.a get_zero.o
gcc -shared -o libget_zero_shared.so -L. -Wl,--whole-archive -lget_zero_static -Wl,-no--whole-archive
这是我得到的错误:
/usr/bin/ld: cannot find -lgcc_s
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libc.a(init-first.o): relocation R_X86_64_32 against `_dl_starting_up' can not be used when making a shared object; recompile with -fPIC
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libc.a(init-first.o): could not read symbols: Bad value
collect2: ld returned 1 exit status
这是在64位Ubuntu系统上.
This is on a 64-bit Ubuntu system.
我在这里了解了整体归档选项,看来这个问题应该消除了我所有的障碍.如何从静态库创建共享对象文件.
I read about the whole-archive option here, and it seemed like this questions should have removed all of my road blocks. How to create a shared object file from static library.
似乎您需要将存档指定为参数,而不是库.因此,使该 libget_zero_static.a
而不是 -lget_zero_static
.至少以这种方式对我有用:
It seems you need to specify the archive as an argument, not as a library. So make that libget_zero_static.a
instead of -lget_zero_static
. At least it works for me this way:
gcc -shared -o libget_zero_shared.so \
-Wl,--whole-archive \
libget_zero_static.a \
-Wl,--no-whole-archive