Assume I have the fowling C code, and I'm compiling it on a linux machine with gcc.
test.c:
#include <stdio.h>
int main() {
printf("hi\n");
return 0;
}
I know that stdio.h defines printf and body of printf exists within the C library in binary format.
Here are my questions:
When doing a normal compile with gcc test.c, does the linker make a dynamic link to printf or a static link?
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.
or in another words: If I open up the executable file and turn in into ascii format, will I see "printf()" in it or "write()"?
C lib will my code still run? since printf isn't defined anywhere anymore.
- When doing a normal compile with
gcc test.c, does the linker make a dynamic link toprintfor 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.
printfultimately makes awrite()system call. Is the linker copying the C lib definedprintfover to the final executable (which will end up callingwrite()at runtime) or is it copyingwrite()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
printfisn'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With