关于stdio.h对应库链接类型及头文件函数加载逻辑的技术咨询
Great questions—let's unpack them clearly, since this gets to how C programs interact with standard libraries under the hood.
1. Is the library containing printf/scanf (backing stdio.h) dynamically linked by default?
It depends on your system and compiler defaults, but most modern systems use dynamic linking for the standard C library (which includes the implementations for printf, scanf, and other stdio.h functions):
- On Linux/Unix-like systems, the standard C library is
libc.so(e.g., glibc). GCC and Clang will dynamically link against this by default unless you explicitly request static linking with the-staticflag. - On Windows, the standard C library is typically
msvcrt.dll(for MSVC) orucrtbase.dll, which are also dynamically linked by default. Again, you can opt for static linking via compiler flags (like/MTin MSVC instead of/MD).
So in most cases, yes—the library behind stdio.h is dynamically linked unless you intentionally change the linking mode.
2. When including stdio.h, are all declared functions loaded at runtime, or only the ones actually used?
First, let's clarify the difference between compilation/linking and runtime:
- Compilation: Including
stdio.honly tells the compiler about the function declarations (signatures) so it can validate your code. It doesn't load any function implementations at this stage. - Linking (dynamic linking): The linker will only note the dependencies for the functions your code actually calls. For example, if you only use
printfand notscanf, the linker won't add a reference toscanfin your executable. - Runtime: When your program runs, the dynamic loader will load the entire standard C library into memory (since dynamic libraries are loaded as whole units), but only the functions your program actually calls will be executed. Many modern systems also use "lazy binding"—meaning the address of a function isn't resolved until the first time it's called, rather than at program startup.
In short: Only the functions your code actually uses will be referenced by the linker, and while the entire dynamic library is loaded into memory at runtime, only the used functions are executed (with lazy binding delaying their resolution until first call).
内容的提问来源于stack exchange,提问作者user8295702

