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

时间:2012-11-05 17:13:04

标签: c linux gcc linker shared-libraries

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

以下是我正在使用的非常简单的源代码。

get_zero.c

#include "get_zero.h"

int
get_zero(void)
{
        return 0;
}

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创建两个功能相同的应用程序。

以下是我的编译/链接步骤:

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系统上。

我在这里阅读了整个档案选项,似乎这些问题应该已经删除了我的所有路障。 How to create a shared object file from static library

2 个答案:

答案 0 :(得分:15)

您似乎需要将存档指定为参数,而不是库。因此,请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

答案 1 :(得分:2)

你可以尝试另一种方式:链接两次,一次用于静态lib,另一次用于共享lib。这应该更容易也更常见。