Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile a shared object (.so) with static glibc

I am building some code that needs to be a shared object (.so).

The problem that the libc on my building machine may be newer than the published machines, so I want to link with it statically to avoid compatibilities issues. (My program uses memcpy which is apparently a GLIBC_2.14 thing when it can go as low as 2.5).

Compiling with both -shared and -static doesn't work since crtbeginT.o wasn't compiled with -fPIC.

Edit: Probably not a duplicate of GCC linking libc static and some other library dynamically, revisited? since that question talking about the main elf linking libc statically and this is about a shared object linking libc statically.

like image 926
Eric. J. Lara Avatar asked Mar 13 '17 13:03

Eric. J. Lara


1 Answers

You want to statically link glibc in your shared library.

You should not do this.

If you try, you will end up with a C++ One Definition Rule (ODR) violation. This is because some parts of glibc will be from the "old" version of your target machine, and some will be from the "new" version of your library. The result is undefined behavior.

The right solution is simple: build with an older glibc (as old as your oldest target for deployment). Or build multiple times, once for each version of glibc you need (if you truly need new glibc features). Even if you think you need a new glibc feature, consider just copy-pasting that one feature into your library under a different name to avoid collisions.

Regarding memcpy in particular, see: https://stackoverflow.com/a/8823419/4323 - and for a manual fix: https://stackoverflow.com/a/5977518/4323

like image 196
John Zwinck Avatar answered Nov 20 '22 02:11

John Zwinck