I mean the math library is dynamically linked.So i was thinking that library files corresponding to stdio.h( printf and scanf codes ) are dynamically linked ? Also when we include stdio.h , then all functions declared in it are added at run time or only those functions which are used ?
-
This is all implementation dependent. – May 04 '18 at 14:47
-
Including is a step of the compilation process, linking is a matter of linkage (static or dynamic)) and runtime (dynamic). On many systems you have the choice to link statically or dynamically. And no, usually the link editor only links with used functions. – Jean-Baptiste Yunès May 04 '18 at 14:49
-
"*usually the link editor only links with used functions.*" <- well, if you call the actual "reference resolving" linking, then yes ... there are some references in a dynamically linked executable and the linker resolves exactly these. But I find this confusing, what's dynamically *linked* is a library, and that's always the **whole** library (it needs to be loaded into RAM as a whole). – May 04 '18 at 18:21
1 Answers
On Linux and many other *nix systems, you typically link the C standard library dynamically, it's the default with gcc
and clang
. But you're still free to link statically if you want to. It entirely depends on your system, environment, toolchain and personal settings.
Also when we include stdio.h , then all functions declared in it are added at run time or only those functions which are used ?
Including a header doesn't link anything. The C standard library is linked automatically by C compilers, otherwise you would get undefined reference errors at the linking step if you use functions that are declared in e.g. stdio.h
.
That said, with dynamic linking, the whole library is loaded at runtime when it is needed by the dynamic linker -- there's no way to load individual functions. The benefit with dynamic linking is that the OS only needs a single copy of this library, no matter how many processes link to it. The library can just be mapped in every processes address-space that needs it. This saves RAM at runtime.