Creating a shared library from a static library using GNU toolchain (gcc/ld)

落花浮王杯 提交于 2021-02-06 10:17:56

问题


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

#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();
}

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

And this is the error I get:

/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

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.


回答1:


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



回答2:


You can just try another way: link twice, once for static lib, and the other for shared lib. That should be easier and more common.



来源:https://stackoverflow.com/questions/13236987/creating-a-shared-library-from-a-static-library-using-gnu-toolchain-gcc-ld

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!