compilation

How is a program that relies on external libraries compiled?


Does every program include a copy of the libraries in the compiled .exe or java file?

What about libraries that supposed to be on every computer, like opengl.dll, etc?


Solution

  • How the program is compiled and how it is linked (whether the libraries are statically linked in or dynamically linked) are two separate issues. I'm going to discuss this for C family languages.

    Programs are compiled against external libraries using header files containing declarations of data types (structs) and functions (prototypes). The compiler can use these declarations to emit calls to the external libraries that respect the platform's application binary interface (ABI), which specifies struct layouts, calling conventions, name mangling, etc -- things the program and the library must agree on to communicate. When compilation is complete, the compiler emits an object file containing external calls to the library functions.

    At link time, the library can be statically linked, meaning a copy of the library's code is integrated in the executable (and if using link-time optimization, further optimizations can be performed). Otherwise, the library will be dynamically linked when the program runs; the dynamic linker uses relocation information in the executable header to patch calls to the library with the address where the linker loaded the external library.

    Dynamic linking relies on the library being available at runtime, but has the advantage of allowing the library to be updated (for security fixes, for example) independently of the program, so long as it exposes the same functions and data types. Dynamic linking can also be delayed until the program actually calls a function in the library, allowing the program to start up more quickly.