I have compiled a variety of .c source codes into their respective .o object files and archived it as a .a archive file. Say in the main() function I use the function foo(). After compiling and linking, does the executable 1) only include the .text of the foo() function as well as all other functions recursively called by foo(), or 2) does it include the entire .o where the foo() resides in, or 3) the .text in the entire .a file?
It is desirable to go for option 1) as it will only include the bare minimum amount of instructions in a space constrained environment. How do I go about accomplishing this?
Normally, the loader will include all the material in all the object files (
.ofiles on Unix/Linux) listed on the link line. If it processes any static libraries (.afiles on Unix/Linux), then the object files that are needed from the library are included in toto (but any object files which do not define a symbol needed by the program are left out of the executable). If it processes any shared libraries (usually.sofiles on Unix/Linux), then it doesn’t load any of the material into the binary, but it does keep a record of all the symbols provided by the shared library, so that it does not try to satisfy any of those symbols from later files or libraries.The loader processes the argument list in left-to-right order. This means that you should list static libraries after object files. It isn’t quite so critical to list shared libraries after object files, though it is still best to do so anyway, just in case the program is ever linked with static libraries instead of shared libraries.
If you end up with doubly defined symbols from the explicitly listed object files or object files extracted from static libraries, then the loader will fail. If you end up with doubly defined symbols in some of the shared libraries, the duplicates in the shared libraries are effectively ignored.
I think that’s a reasonable summary written at high speed and not getting too lost in the details. There’s a lot of if’s and but’s that could be added to the discussion; whole books have been written on the subject of how executables are created from object files and libraries.