简体   繁体   中英

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

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.

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. 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

Reference-2

In your above example you need to use -fPIC when compiling object files for your static library. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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