Does linking and loading of the the dynamic libraries both happen at runtime? or is it that only loading of the library happens at run time?
See the earlier very good point about the distinction between static linking and dynamic linking. Assuming you are referring to the dynamic linking, then:
Both loading and (dynamic) linking are done by the linker – on linux and other Unix-alikes this is done by /lib/ld.so
, which is the actual program that is launched by the operating system in almost all cases. ld.so
in turn loads your application - mygameBinary
into memory, and ld.so
then reads from the file mygameBinary
the list of dynamic linked libraries that it requires.
The linker, ld.so
, then loads each of these libraries into memory in turn, e.g. libc.so
, libpthread.so
, libopengl.so
, and looks at what other libraries these might require, e.g. libm.so
.
Once loading is done, then linking begins, a process of looking at named objects or functions which are exported by one library or the application, and imported by another library or application. The linker then changes various references and sometimes code to update unlinked data pointers and function calls in each library to point where the actual data or function resides. For example, a call to printf
in mygameBinary
starts off pointing at nothing (actually it just calls the linker), but after linking becomes a jump to the printf
function in libc
.
Once this linking is complete, the application is started, by invoking the _start
function in mygameBinary
, which then calls main
, and your game starts.
Dynamic linking in this way is necessary to support the following:
Some OSs differ in the details, for instance OSX and AIX both pre-load a certain set of libraries into fixed locations in memory. This means they don't need to be loaded, just linked, which may be faster.
Some OSs such as OSX and sometimes Linux support pre-linking, which is a process where a script runs over the applications on your system before you launch them, and does the linking. When you launch them, you then don't need to link them. This is important because linking takes a considerable amount of your computer's time when you launch an app, and some apps may be launched multiple times a second, such as gcc
, cpp
and as
during application build process, or filter scripts when indexing your computer's data (OSX Spotlight).