I have heard that my C++ programs \"need to link with the C++ library/runtime\".
ID: 655040 • Letter: I
Question
I have heard that my C++ programs "need to link with the C++ library/runtime". However, the C++ runtime is just the compiler inserting stack operation code in to the image, or "boilerplate" code if you will. The C++ runtime is basically intrinsic to the program itself, so "linking the runtime" is a bit illogical. Linking a library makes more sense, especially since the C++ libraries are independent objects which would otherwise need resolvement with the source program itself, and relocation.
So I wondered, besides the C++ library, what else, or how do you know what you are linking with exactly? For example, if I'm supposedly linking with the C++ library, I also need to link with the OS-specific library and API as well, or at least a wrapper of some sort that will deal directly with it.
So the linker will, in effect, link the main program file with the C++ library with the OS-API/library? That doesn't sound particularly right.
Basically, the linker will link multiple libraries together(statically, in this example, at compile/link-time)?
Explanation / Answer
On Unix and Linux, you can see which libraries are linked with the ldd command. The output from an empty c++ program I made as a test was:
linux-gate.so.1 (0xb77ba000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb76ae000)
libm.so.6 => /usr/lib/libm.so.6 (0xb7668000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb764c000)
libc.so.6 => /usr/lib/libc.so.6 (0xb749c000)
/lib/ld-linux.so.2 (0xb77bb000)
linux-gate and ld-linux are treated specially by the linker. The rest are all more or less regular libraries. They are all open source, so you can see precisely what they do. Search for "libstdc++ source" for example.
They basically contain implementations for anything that is too long to inline: standard library containers, memory allocation, trigonometry, sockets, file handles, etc. These implementations are highly specific to architecture and operating system. They make calls into the kernel for the operating system they were compiled for. I've had to implement several libc functions for a custom embedded operating system.