I don’t understand how GCC works under Linux. In a source file, when I do a:
#include <math.h>
Does the compiler extract the appropriate binary code and insert it into the compiled executable OR does the compiler insert a reference to an external binary file (a-la Windows DLL?)
I guess a generic version of this question is: Is there an equivalent concept to Windows DLLs under *nix?
Well. When you include
math.hthe compiler will read the file that contains declarations of the functions and macros that can be used. If you call a function declared in that file (header), then the compiler inserts a call instruction into that place in your object file that will be made from the file you compile (let’s call ittest.cand the object file createdtest.o). It also adds an entry into the relocation table of that object-file:This would be a relocation entry for a function bar. An entry in the symbol table will be made noting the function is yet undefined:
When you link the
test.oobject file into a program, you need to link against the math library calledlibm.so. Thesoextension is similar to the.dllextension for windows. It means it is a shared object file. The compiler, when linking, will fix-up all the places that appear in the relocation table oftest.o, replacing its entries with the proper address of the bar function. Depending on whether you use the shared version of the library or the static one (it’s calledlibm.athen), the compiler will do that fix-up after compiling, or later, at runtime when you actually start your program. When finished, it will inject an entry in the table of shared libraries needed for that program. (can be shown withreadelf -d ./test):Now, if you start your program, the dynamic linker will lookup that library, and will link that library to your executable image. In Linux, the program doing this is called
ld.so. Static libraries don’t have a place in the dynamic section, as they are just linked to the other object files and then they are forgotten about; they are part of the executable from then on.In reality it is actually much more complex and i also don’t understand this in detail. That’s the rough plan, though.