使用GNU工具链(gcc/ld)从静态库创建共享库

use*_*585 13 c linux linker gcc shared-libraries

我在从静态库生成共享对象时遇到问题.虽然我知道还有其他选择,但我现在很困扰(而不是卡住)为什么这不起作用以及如何使其发挥作用.

下面是我正在使用的非常简单的源代码.

get_zero.c

#include "get_zero.h"

int
get_zero(void)
{
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

get_zero.h

int get_zero(void);
Run Code Online (Sandbox Code Playgroud)

main.c中

#include <stdio.h>
#include <string.h>

#include "get_zero.h"

int
main(void)
{
    return get_zero();
}
Run Code Online (Sandbox Code Playgroud)

目标是使用libget_zero_static和libget_zero_shared创建两个功能相同的应用程序.

这是我的编译/链接步骤:

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
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

/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
Run Code Online (Sandbox Code Playgroud)

这是在64位Ubuntu系统上.

我在这里阅读了关于整个存档选项,似乎这些问题应该已经删除了我的所有路障. 如何从静态库创建共享对象文件.

MvG*_*MvG 16

您似乎需要将存档指定为参数,而不是库.所以,libget_zero_static.a而不是-lget_zero_static.至少它对我有用:

gcc -shared -o libget_zero_shared.so \
-Wl,--whole-archive                  \
libget_zero_static.a                 \
-Wl,--no-whole-archive
Run Code Online (Sandbox Code Playgroud)