Home >Backend Development >C++ >How Does C Linking Work: From Object Files to Executable?
How does C linking work in practice?
In C , linking is the process of combining multiple object files (.o files) and libraries (.a or .so files) into a single executable file (.exe or .out). The linker resolves external references between object files and libraries, and creates a symbol table and other information necessary for the executable to run.
How does linking happen?
Relocation in Practice
To illustrate the process of relocation, consider the following example:
// a.cpp int a = 10; int main() { return a; }
// b.cpp int b = 20;
When we compile a.cpp and b.cpp, we get two object files: a.o and b.o. The a.o file contains the definition of the variable a, while b.o contains the definition of the variable b.
When we link a.o and b.o together, the linker needs to make sure that the references to a and b in the final executable point to the correct addresses. This is done by performing relocation.
During relocation, the linker modifies the addresses of a and b in the executable to match their final addresses in memory. For example, if a is allocated at address 0x1000 and b is allocated at address 0x2000, the linker will modify all references to a in the executable to point to 0x1000, and all references to b to point to 0x2000.
This process ensures that the executable can correctly access the variables a and b when it runs.
The above is the detailed content of How Does C Linking Work: From Object Files to Executable?. For more information, please follow other related articles on the PHP Chinese website!