简体   繁体   English

LD:将共享库链接到静态库

[英]LD: Linking a shared library to a static library

I am trying to link a static library with shared library and this throws me an error saying recompile with -fPIC 我正在尝试将static libraryshared library链接,这引发了一个错误recompile with -fPIC

Here's what I have tried using an example: 这是我尝试使用的示例:

savari@Ramana:~/Junk$ cat common.h 
#include <stdio.h>
#include <stdlib.h>

void func1(int *p);
void func2();

Shared library code: 共享库代码:

savari@Ramana:~/Junk$ cat shared.c 
#include "common.h"

void func2()
{
    int i=10;
    func1(&i);
}

And the static library code: 和静态库代码:

#include "common.h"

int k;

void func1(int *p)
{
    printf("%d\n", *p);
}

Now, see that the shared library uses the API of static library. 现在,看到共享库使用静态库的API。

Here's how I compiled: 这是我的编译方式:

gcc -c static.c

ar rcs libStatic.a static.o

gcc -c shared.c

gcc -shared -fPIC -o libShared.so shared.o  -L. -lStatic

After the last command, I get the following error: 最后一条命令后,出现以下错误:

/usr/bin/ld: ./libStatic.a(static.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
./libStatic.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status

I actually got static library from a vendor and I am trying to build a shared library on top of it. 我实际上是从供应商那里获得的static library ,我正在尝试在其上构建一个shared library I don't have the source of static library. 我没有静态库的来源。

I get other type of error saying: 我收到其他类型的错误信息:

relocation R_ARM_THM_MOVW_ABS_NC against `a local symbol' can not be used when making a shared object; recompile with -fPIC
error adding symbols: Bad value
collect2: error: ld returned 1 exit status

I went through so many articles, but couldn't able to figure out. 我读了很多文章,但无法弄清楚。 Please help me fix this. 请帮我解决这个问题。

References: 参考文献:

Reference-1 参考1

Reference-2 参考2

In your above example you need to use -fPIC when compiling object files for your static library. 在上面的示例中,在为静态库编译目标文件时需要使用-fPIC If you omit this option the compiled code just cannot be wrapped into a shared object. 如果省略此选项,则编译后的代码将无法包装到共享库中。 If you only have the static library and no source code there is nothing you can do about it. 如果您只有静态库而没有源代码,那么您将无能为力。 Ask the creator of the library to provide you with a compile where -fPIC is enabled. 请库的创建者为您提供启用-fPIC的编译器。

试试这个静态链接libStatic.a:

gcc -shared -fPIC -o libShared.so shared.o  -L. -Wl, -Bstatic -lStatic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM