views:

114

answers:

2

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.

+7  A: 

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.

Matthew Flaschen
+3  A: 

A library contains previously compiled object code - basically a static library is an archive of .o or .obj files.

The linker looks at your object code and sees if there are any unresolved names and if so looks for these in the library, if it finds them it includes the object file that contains them and repeats this.

Thus only the parts of the static library that are needed are included in your executable.

Thus in your case nothing from libfoo will be added to you executable

Mark