- When doing a normal compile with
gcc test.c
, does the linker make a dynamic link to printf
or a static link?
It depends. Given that specific compilation command, if a dynamic version of the C library is available, and if GCC is built to use it (both of which are highly likely), then GCC will perform a dynamic link. If only a static version of the C library is available, or if GCC is built or configured to link statically by default, then a static link will be performed.
printf
ultimately makes a write()
system call. Is the linker copying the C lib defined printf
over to the final executable (which
will end up calling write()
at runtime) or is it copying write()
over in the final executable directly.
If GCC is performing a static link then it will copy all functions directly or indirectly required by the program, and maybe others, into the final binary. I'm uncertain about the GNU linker in particular, but some linkers will include the whole target library in the final binary.
- If I compile my code and then uninstall the C lib will my code still run? since
printf
isn't defined anywhere anymore.
If you statically link the C library into your program, then removing the C library afterward will not (directly) prevent your program running. But depending on the details, it might prevent everything else from running, including the GUI, your other applications, and even the shell, thus mooting the question.
Statically linking all required libraries is a reasonable technique for minimizing the runtime dependencies of your binaries, which can improve compatibility with systems differing from the build environment. That does tend to produce much larger binaries, however. In any case, unless you build every program that way, removing the libraries after the fact is not usually a viable alternative.