Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and C++ static linking: just a copy?

When someone statically links a .lib, will the linker copy the whole contents of lib into the final executable or just the functions used in the object files?

like image 397
George Avatar asked Mar 16 '11 22:03

George


2 Answers

  • The whole library? -- No.
  • Just the functions you called? -- No.
  • Something else? -- Yes.

It certainly doesn't throw in the whole library.

But it doesn't necessarily include just "the functions used in the object files" either.

The linker will make a recursively built list of which object modules in the library satisfy your undefined symbols.

Then, it will include each of those object modules.

Typically, a given object module will include more than one function, and if some of these are not called by the ones that you do call, you will get some number of functions (and data objects) that you didn't need.

like image 118
DigitalRoss Avatar answered Sep 22 '22 22:09

DigitalRoss


The linker typically does not remove dead code before building the final executable. That is, it will (usually) link in ALL symbols whether they are used in the final executable or not. However, linkers often explicitly provide Optimization settings you can use to force the linker to try extra hard to do this.

For GCC, this is accomplished in two stages:

  1. First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:

    -fdata-sections -ffunction-sections

  2. Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):

    -Wl,--gc-sections

So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):

gcc -Os -fdata-sections -ffunction-sections test.cpp -o test.o -Wl,--gc-sections

(Note that -Os is an additional compiler flag that tells GCC to optimize for size)

As for MSVC, function level linking accomplishes the same thing. I believe the compiler flag for this is (to sort things into sections):

/Gy

And then the linker flag (to discard unused sections):

/OPT:REF
like image 22
J T Avatar answered Sep 23 '22 22:09

J T