0

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

Ramana Reddy
  • 369
  • 1
  • 8
  • 28

2 Answers2

0

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.

Florian Zwoch
  • 6,764
  • 2
  • 12
  • 21
  • Can we use `-fPIC` for static library?. Anyway I gave a try using `-fPIC` as in `gcc -c static.c -fPIC` which throws the same error – Ramana Reddy Dec 15 '17 at 10:42
  • 1
    You need to compile all your objects that are part of the lib with `-fPIC`. So add it to the shared.c too. Have you recreated your `.a` with the updated object? – Florian Zwoch Dec 15 '17 at 11:45
0

try this to statically link libStatic.a:

gcc -shared -fPIC -o libShared.so shared.o  -L. -Wl, -Bstatic -lStatic
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37