Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static link libpng into a shared library

I've reduced the problem to this minimal test.c:

#include "png.h"

int function() {
    printf("%ld", (long)png_create_read_struct);
}

Compiling with

gcc -shared -fPIC test.c -o test.so -lm -l:libpng16.a

gives the error

/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/6/../../../x86_64-linux-gnu/libpng16.a(pngread.o): relocation R_X86_64_PC32 against symbol `png_sRGB_table' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value

Now every answer I've found to this error boils down to "do what it says and recompile with -fPIC", but as you can see I'm already doing that. So what gives?

(Output above is from Ubuntu 17.10 with libpng16. Ubuntu 16.04 with libpng12 results in similar error.)

like image 409
Pedro Lopes Avatar asked Nov 29 '25 06:11

Pedro Lopes


1 Answers

Compiling libpng with -fPIC

user@user_pc:~/Documents$ mkdir libpng
user@user_pc:~/Documents$ cd libpng
user@user_pc:~/Documents/libpng$ wget https://download.sourceforge.net/libpng/libpng-1.6.37.tar.gz
user@user_pc:~/Documents/libpng$ tar xvfz libpng-1.6.37.tar.gz
user@user_pc:~/Documents/libpng$ cd libpng-1.6.37
user@user_pc:~/Documents/libpng/libpng-1.6.37$./configure --prefix=/home/user/Documents/libpng --with-pic=yes
user@user_pc:~/Documents/libpng/libpng-1.6.37$ sudo make

Your binaries are in ~/Documents/libpng/libpng-1.6.37/lib, most interesting one is libpng.a which was now compiled with -fPIC.

It also solves problem when compiling blender on Linux as a Python module:

/usr/bin/ld.gold: error: /usr/lib/x86_64-linux-gnu/libpng.a(pngerror.o): requires dynamic R_X86_64_PC32 reloc against 'stderr' which may overflow at runtime; recompile with -fPIC
collect2: error: ld returned 1 exit status
like image 94
Christopher Avatar answered Dec 01 '25 21:12

Christopher