Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does static linking against a library actually do?

Say I had a library called libfoo which contained a class, a few static variables, possibly something with 'C' linkage, and a few other functions.

Now I have a main program which looks like this:

int main() {
   return 5+5;
}

When I compile and link this, I link against libfoo.

Will this have any effect? Will my executable increase in size? If so, why? Do the static variables or their addresses get copied into my executable?

Apologies if there is a similar question to this or if I'm being particularly stupid in any way.

like image 397
Salgar Avatar asked Dec 28 '22 15:12

Salgar


1 Answers

It won't do anything in a modern linker, because it knows the executable doesn't actually use libfoo's symbols. With gcc 4.4.1 and ld 2.20 on my system:

g++ linker_test.cpp -static -liberty -lm -lz -lXp -lXpm -o linker_test_unnecessary
g++ linker_test.cpp -static -o linker_test_none
ls -l linker_test_unnecessary linker_test_none 

They are both 626094 bytes. Note this also applies to dynamic linking, though the size they both are is much lower.

like image 93
Matthew Flaschen Avatar answered Jan 13 '23 16:01

Matthew Flaschen