【问题标题】:Creating a shared library from a static library using GNU toolchain (gcc/ld)使用 GNU 工具链 (gcc/ld) 从静态库创建共享库
【发布时间】:2012-10-25 13:50:42
【问题描述】:

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

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

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.

【问题讨论】:

标签: c linux gcc linker shared-libraries


【解决方案1】:

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

【讨论】:

  • 是的。那将是正常的路线,但正如我所说的 cmets 我认为这种方法应该是可能的。我只是不明白为什么它不起作用。
【解决方案2】:

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

【讨论】:

  • 这并没有解决我的问题。你是运行 32 位的吗?我很确定这在 32 位系统上对我有用。
  • @user442585:64 位使用 gcc 4.6.3 和 ld 2.23。也可以使用其他几个 gcc 版本,所以我会说这可能是由于 ld 版本。你得到什么错误?与您在问题中粘贴的相同吗?这次编译器标志中的-fPIC 会不会丢失?
  • 从来没有想过这个,哦,好吧.....你付出了最大的努力,所以你得到了答案:)
猜你喜欢
  • 2011-05-17
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
相关资源
最近更新 更多