0
votes

I am trying to generate a shared library (libgenerated.so) using g++ . The shared library uses some functionality that comes from a third party static library (libmystatic.a). For which I am linking the static library with the shared library as :

g++ -shared -o libgenerated.so $(OBJ_FILES) -lmystatic

The above command returns the following relocation error for the static library:

relocation R_X86_64_32S against `.rodata' can not be used when making a shared object; recompile with -fPIC

Which points out that the object files in the static library needs to be compiled with -fpic flag. I am unable to understand why creating a Windows dll using the same static library (compiled for windows without -fpic) works ? I am using x86_64-w64-mingw32-g++ for the Windows DLL.

Thoughts from experts....

1
Because PIC is the default on Windows, so you don't need this flag. - n. 1.8e9-where's-my-share m.
Does this mean that object files compiled with mingw are by default position independent ? - sbunny
Yes this is my understanding. - n. 1.8e9-where's-my-share m.

1 Answers

0
votes

Which points out that the object files in the static library needs to be compiled with -fpic flag.

Exactly: on x86_64 you must compile code that is linked into a shared library with -fPIC of -fPIC.

I am unable to understand why creating a Windows dll using the same static library (compiled for windows without -fpic) works ?

There are two reasons:

  1. On Windows, position-independent code is the default. So you get code compiled as if -fPIC was on command line regardless of whether that flag was on compile line or not.
  2. The requirement to have position-independent code is architecture-specific. You can build a 32-bit i*86 shared library without -fPIC (this is ill-advised, but it works). On x86_64 (64-bit) Linux, you can't -- it simply can't work on that architecture.