Sam D20
Sam D20

Reputation: 2575

Statically linking libc into my binary causes it to segfault

I need to build a binary with libc statically linked. I have libc.a available in the same directory as the source code. To compile, I tried the following:

gcc -o foo foo.c libc.a 

This resulted in the following issue:

/usr/bin/ld: dynamic STT_GNU_IFUNC symbol `strcmp' with pointer equality in `libc.a(strcmp.o)' can not be used when making an executable

In researching this, I found the following question: Linking partially static and partially dynamic in GCC

Following the solution in the top answer, I created my own string comparison function in my_strcmp.c and tried the following compilation:

gcc -o foo foo.c mystrcmp.c libc.a 

And it works, but the binary now segfaults quite early. This doesn't happen without libc statically linked. Here's the GDB trace:

(gdb) backtrace                                
#0  0x00000000004fe48e in generic_start_main ()
#1  0x00000000004fe891 in __libc_start_main () 
#2  0x0000000000406b56 in _start ()  

Not really sure how to interpret this. Anyone have any ideas?

Upvotes: 2

Views: 858

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215257

If you want to produce a static-linked binary, just add -static to the command line. You do not need libc.a there at all. What you're doing, adding libc.a without -static, produces a dynamic-linked binary, but pulls in some functions/files (whatever you reference, and everything those reference, recursively) from libc.a, and still also has the shared libc.so participating in your program. These are not generally able to work together.

Upvotes: 5

Related Questions