Chapter 2 – Programming language: Building process
Compilation process can be split in three steps:
- Compilation + Assembler
Preprocessing deals with preprocessor directives (includes and macros).
Compilation process parses the code, converts it into assembly code, which is then converted to machine code (0 and 1) – creating object files. Common error cases that may occur at this step are undeclared functions, or parsing errors (missing ; ).
Linking links all the object files by replacing the references to undefined symbols with the correct addresses (that are found in other obj files or in libraries). Common error cases that may occur at this step are libraries not being linked with the application, multiple definition, or undefined reference to main (main function not found).
Libraries are files that contain reusable code, which can be used in other libraries or executable. They are invoked directly by other code, once the library is loaded.
Static libraries (.a, .lib)
A static library is a set of functions and variables which are resolved at compile-time and copied into a target application.
Dynamic libraries (.so, .dll)
A dynamic library is a set of functions and variables which are resolved at runtime.
Dynamic linking (late-binding) is performed while a program is being loaded (load time) or executed (runtime).
Static vs dynamic libraries
If we were to talk about the differences between using static or dynamic libraries, there are many things to take into account, for example:
- Binary size: The binary size is higher for static libraries, because the code is copied directly into the executable
- Performance: Static libraries are able to optimize the code better since they have access to the implementation
- Reusability / code sharing: If we have multiple executables using the same static library, the code is copied in all of them, whereas with dynamic library, we can load only one into the system and share the memory location to both / all executables
- Maintainance: In case we want to add or change functionality, it’s easier to use dynamic libraries and simply swap a dll, instead of rebuilding and delivering the entire software to the client.
- Licensing: This is usually forgotten, but if we use LGPL licensed code and link it statically, our code becomes Open sourced LGPL code – so we need to share it with the world. The solution here is to link dynamic library, so the code will remain closed-source.