1. What Is a Program Build?
A program build (Build) is the process of converting source code and its dependencies into a runnable program or other deliverable artifact.
Code written by programmers usually cannot be executed directly by the CPU.
For example, consider a piece of C code:
#include <stdio.h>
int main(void) {
int a = 10;
int b = 20;
int result = a + b;
printf("result = %d\n", result);
return 0;
}
This code contains:
int: a data type.main: the program entry function.a + b: an arithmetic expression.printf: a standard library function call.return: a function return operation.
These elements belong to the syntax and semantics of a high-level language; they are not instructions that the CPU can execute directly.
The CPU executes machine instructions corresponding to the processor's instruction set architecture, such as x86-64, ARM64, or RISC-V instructions.
Therefore, a program needs to go through a series of transformations:
flowchart TD
A["Source code"] --> B["Preprocessing"]
B --> C["Compilation"]
C --> D["Assembly"]
D --> E["Object file"]
E --> F["Linking"]
F --> G["Executable file"]
G --> H["OS loading"]
H --> I["CPU execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style I fill:#F1F3F5,stroke:#C9D0D8,color:#334155
A program build mainly solves the following problems:
- Convert high-level language code into code that the target platform can execute.
- Organize multiple source files into a complete program.
- Resolve dependencies among functions, variables, and libraries.
- Lay out code and data for the program.
- Generate files that the operating system can recognize and load.
Two concepts need to be distinguished:
- Compile: Convert source code into object code.
- Build: Organize the complete engineering process of compilation, linking, resource processing, testing, and packaging.
Compilation is only one stage in the build process.
2. What Tools Are Involved in a Program Build?
Taking C and C++ as examples, a complete build toolchain usually includes the following components.
| Tool | Primary responsibility | Common tools |
|---|---|---|
| Preprocessor | Expands header files and macros | GCC CPP |
| Compiler | Analyzes source code and generates assembly or object code | GCC, Clang |
| Assembler | Converts assembly into machine code | GNU as |
| Linker | Merges object files and resolves symbols | GNU ld, LLD |
| Build system | Manages file dependencies and build tasks | Make, Ninja |
| Build configuration tool | Generates build rules | CMake |
| Debugging tool | Analyzes programs and symbol information | GDB, LLDB |
| Binary analysis tool | Inspects object files and executables | readelf, objdump |
1. Compiler
The compiler is responsible for converting high-level language code into a representation closer to the target platform.
For example:
gcc -S main.c -o main.s
This command asks GCC to generate assembly code rather than a final executable.
2. Assembler
The assembler is responsible for converting assembly instructions into machine code and generating object files.
For example:
as main.s -o main.o
You can also use GCC directly to complete the assembly stage:
gcc -c main.s -o main.o
3. Linker
The linker is responsible for organizing multiple object files and libraries and resolving cross-file references to functions and variables.
For example:
gcc main.o math.o -o app
The linker here needs to handle the symbol dependencies between main.o and math.o.
4. Build System
Large projects often contain dozens, hundreds, or even thousands of source files.
Recompiling the entire project every time the code changes wastes a lot of time.
The build system is responsible for:
- Managing dependencies between source files and object files.
- Determining which files need to be recompiled.
- Controlling compilation order.
- Managing parallel builds.
- Unifying compilation parameters.
- Executing test and packaging tasks.
Common tools include Make, CMake, and Ninja.
III. Stage 1: Preprocessing
Preprocessing is an important stage in the C and C++ build process.
It mainly handles preprocessing directives that begin with #.
For example:
#include <stdio.h>
#define MAX_SIZE 100
int main(void) {
int size = MAX_SIZE;
printf("%d\n", size);
return 0;
}
The preprocessor needs to complete the following tasks.
1. Handling Header Files
The #include directive is used to include other files.
For example:
#include <stdio.h>
#include "config.h"
Among them:
- Angle brackets are usually used to search system or configured header file directories.
- Double quotes usually search the directory containing the current source file first, then other configured directories.
The exact search order depends on the compiler and compilation parameters.
Suppose config.h defines:
#define APP_NAME "Demo"
#define APP_VERSION 1
Then the preprocessor will expand the contents of the corresponding header file into the current source file.
2. Handling Macro Definitions
For example:
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
int main(void) {
double area = PI * SQUARE(5);
return 0;
}
The preprocessor expands macros.
With function-like macros, you need to watch out for argument side effects, for example:
#define SQUARE(x) ((x) * (x))
int result = SQUARE(i++);
Here i++ will be expanded and used twice, which may cause unexpected behavior.
Therefore, function-like macros are not equivalent to ordinary functions.
3. Conditional Compilation
Conditional compilation can determine which code participates in compilation based on macro definitions.
#ifdef DEBUG
printf("Debug mode\n");
#else
printf("Release mode\n");
#endif
At compile time, you can specify:
gcc -DDEBUG main.c -o main
Here -DDEBUG means defining the DEBUG macro.
4. Viewing the Preprocessing Result
Create main.c:
#include <stdio.h>
#define VALUE 100
int main(void) {
printf("%d\n", VALUE);
return 0;
}
Execute:
gcc -E main.c -o main.i
View the result:
head -n 30 main.i
Preprocessed files usually have the .i extension.
Common GCC options:
| Option | Purpose |
|---|---|
-E |
Run preprocessing only |
-I |
Add a header file search directory |
-D |
Define a macro |
-U |
Undefine a macro |
-include |
Force inclusion of the specified header file |
IV. Stage 2: Compilation
Compilation is responsible for converting the preprocessed source code into code related to the target architecture.
A compiler usually consists of a front end, an intermediate representation, and a back end.
flowchart TD
A["Preprocessed source code"] --> B["Lexical analysis"]
B --> C["Syntax analysis"]
C --> D["Abstract syntax tree AST"]
D --> E["Semantic analysis"]
E --> F["Intermediate representation IR"]
F --> G["Code optimization"]
G --> H["Target code generation"]
H --> I["Assembly code"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style I fill:#F1F3F5,stroke:#C9D0D8,color:#334155
1. Lexical Analysis
The lexer splits the source code into tokens.
For example:
int result = a + 10;
It can be split into:
| Token | Type |
|---|---|
int |
Keyword |
result |
Identifier |
= |
Assignment operator |
a |
Identifier |
+ |
Arithmetic operator |
10 |
Integer literal |
; |
Separator |
2. Syntax Analysis
The parser checks whether the tokens conform to the language grammar and builds an abstract syntax tree.
For example:
int result = a + b * 2;
Its core structure can be represented as:
Variable declaration
├── Type: int
├── Variable name: result
└── Initialization expression
├── Addition
│ ├── a
│ └── Multiplication
│ ├── b
│ └── 2
The abstract syntax tree makes the structure of the expression and operator precedence explicit.
3. Semantic Analysis
Semantic analysis checks whether the code conforms to the semantic rules of the language.
For example:
int age = "hello";
In C, this involves an incompatible type conversion issue.
Semantic analysis also needs to check:
- Whether variables are declared.
- Whether variable scope is valid.
- Whether functions exist.
- Whether the number and types of arguments are correct.
- Whether the return value matches the function declaration.
- Whether there are invalid type operations.
4. Intermediate Representation IR
Intermediate representation (IR) is a program representation used internally by compilers.
For example:
int result = a + b * 2;
It can be converted into a three-address form like the following:
t1 = b * 2
t2 = a + t1
result = t2
IR allows a compiler to separate the language frontend from the target platform backend.
For example, LLVM can use a unified LLVM IR to support different languages and different target architectures.
Example:
define i32 @add(i32 %a, i32 %b) {
entry:
%result = add i32 %a, %b
ret i32 %result
}
5. Code Optimization
Compilers optimize code while ensuring that the program semantics remain unchanged.
Common optimizations include:
| Optimization Technique | Description |
|---|---|
| Constant folding | Precompute constant expressions |
| Constant propagation | Propagate known constants into other expressions |
| Dead code elimination | Remove code that does not affect the result |
| Common subexpression elimination | Avoid duplicate computation |
| Function inlining | Inline function calls |
| Loop optimization | Reduce redundant operations in loops |
| Register allocation | Use CPU registers efficiently |
| Instruction scheduling | Reorder instructions to improve execution efficiency |
For example:
int a = 10 * 20;
int b = a + 5;
The compiler may compute the following directly during compilation:
int a = 200;
int b = 205;
The actual optimization effect depends on the optimization level and context.
6. Target Code Generation
The compiler backend translates IR into assembly or machine code for the target architecture.
The same C code:
int add(int a, int b) {
return a + b;
}
may generate different instructions on x86-64 and ARM64.
The reason is that different processors have different:
- Instruction sets.
- Register organization.
- Calling conventions.
- Memory addressing modes.
- Instruction encoding formats.
7. Inspecting Compilation Results
Generate an assembly file:
gcc -S -O0 main.c -o main.s
Enable optimization:
gcc -S -O2 main.c -o main_O2.s
View the assembly:
cat main.s
Compare different optimization levels:
diff -u main.s main_O2.s
By comparing them, you can observe the effect of optimization on the assembly code.
V. Stage Three: Assembly
Assembly is responsible for converting assembly language into machine code.
Assembly language is a readable form of machine instructions.
For example, in x86-64 assembly:
mov eax, 10
add eax, 20
means placing 10 into a register and then performing addition.
The corresponding machine code is instruction encoding composed of binary bytes.
1. What Does the Assembler Do?
The assembler is mainly responsible for:
- Parsing assembly instructions.
- Converting mnemonics into machine instruction encodings.
- Handling labels and symbols.
- Generating relocation information.
- Organizing code and data sections.
- Generating object files.
2. What Is an Object File?
An object file is an intermediate product generated by the assembler.
Common extensions:
.o: Common on Linux, Unix, and similar systems..obj: Common in Windows toolchains.
An object file usually contains:
| Content | Purpose |
|---|---|
| Machine instructions | Executable program code |
| Data section | Global variables and static data |
| Symbol table | Records function and variable symbols |
| Relocation information | Records addresses that need later correction |
| Debug information | Supports source-level debugging |
Note that an object file usually has not resolved all external symbol references, so it may not be able to run independently.
3. Generating an Object File with GCC
gcc -c main.c -o main.o
Check the file type:
file main.o
View the object file header:
readelf -h main.o
View the sections:
readelf -S main.o
View the symbol table:
readelf -s main.o
View relocation information:
readelf -r main.o
View the disassembly:
objdump -d main.o
These tools help us observe the actual output generated by the compiler.
VI. Internal Structure of Object Files
Understanding object files is the foundation for understanding the linking process.
On Linux systems, GCC usually generates object files in ELF format.
ELF stands for Executable and Linkable Format, the format for executable and linkable files.
1. Main Components of an ELF File
An ELF file mainly consists of the following structures:
- ELF Header: the file header.
- Program Header Table: the program header table.
- Section Header Table: the section header table.
- Sections: sections.
Not all ELF files have a program header table. For example, ordinary relocatable object files generally rely mainly on section information, while executable files and shared libraries usually contain a program header table.
2. Common ELF Sections
| Section | Purpose |
|---|---|
.text |
Stores machine instructions |
.rodata |
Stores read-only data |
.data |
Stores initialized writable global data |
.bss |
Stores static storage duration data that is not explicitly initialized or is initialized to zero |
.symtab |
Symbol table |
.strtab |
String table |
.rel.* |
Relocation information, commonly found in some object files |
.rela.* |
Relocation information with an explicit addend |
.debug_* |
Debugging information |
Among them, .text, .data, and .bss are important parts for understanding a program's memory layout.
3. The .text Code Section
.text usually stores the machine instructions corresponding to functions.
For example:
int add(int a, int b) {
return a + b;
}
After compilation, the machine instructions corresponding to the add function are usually located in the .text section.
4. The .data Data Section
.data stores writable data that requires initial contents to be stored, such as data with static storage duration that is explicitly initialized to a non-zero value.
For example:
int global_count = 100;
5. The .bss Uninitialized Data Section
.bss is usually used to store static storage duration objects that are not explicitly initialized or are initialized to zero.
For example:
int global_count;
static int cache_size;
.bss usually does not need to store large amounts of repeated zero bytes in the file; instead, the required memory is described by information such as the section size.
6. Differences Between Object Files and Process Memory
Sections in an object file are not equivalent to the complete memory layout of a program at runtime.
The linker organizes input sections to form output sections; the loader then maps the program into the process address space based on the segment information in the program header table.
A distinction should be made:
- Section: mainly serves compilation, linking, and file organization.
- Segment: mainly serves program loading and memory mapping.
flowchart TD
A["ELF Object File"] --> B["Sections"]
B --> C[".text"]
B --> D[".rodata"]
B --> E[".data"]
B --> F[".bss"]
B --> G["Symbol table and relocation information"]
C --> H["Linker organizes output sections"]
D --> H
E --> H
F --> H
G --> H
H --> I["Program segments of the executable file"]
I --> J["Loader establishes memory mapping"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#F1F3F5,stroke:#C9D0D8,color:#334155
VII. Stage Four: Linking
Linking is responsible for combining multiple object files and libraries to generate a complete program.
In large projects, a program is usually composed of multiple source files.
For example:
project/
├── main.c
├── math.c
└── math.h
main.c:
#include <stdio.h>
#include "math.h"
int main(void) {
int result = add(10, 20);
printf("%d\n", result);
return 0;
}
math.h:
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
#endif
math.c:
int add(int a, int b) {
return a + b;
}
Here, main.c calls the add function defined in math.c.
During compilation, the compiler can check whether the call is legal based on the declaration in the header file, but main.o still needs to reference the external add symbol.
This reference must be handled by the linker.
1. The linker's main job
The linker is mainly responsible for:
- Collecting object files and library files.
- Reading the symbol table of each file.
- Resolving external symbol references.
- Merging related sections.
- Allocating the address layout in the output file.
- Handling relocations.
- Generating an executable file or shared library.
2. What is a symbol?
A symbol is a name used during linking to identify entities such as functions and variables.
For example:
int add(int a, int b) {
return a + b;
}
Here add is a function symbol.
Consider another example:
extern int global_value;
int get_value(void) {
return global_value;
}
global_value is an external variable symbol.
A symbol table usually records:
- The symbol name.
- The symbol type.
- The symbol binding attribute.
- The section it belongs to.
- The symbol value.
- The symbol size.
You can use:
nm main.o
to view the symbols in an object file.
Common symbol type markers include:
| Marker | Common meaning |
|---|---|
T |
Global code symbol |
t |
Local code symbol |
D |
Initialized global data |
B |
BSS data |
U |
Undefined symbol |
R |
Read-only data |
The exact markers are affected by the object file format and the tool implementation.
3. What is an undefined symbol?
Suppose:
main.c:
int add(int a, int b);
int main(void) {
return add(10, 20);
}
math.c:
int add(int a, int b) {
return a + b;
}
Compile main.c on its own:
gcc -c main.c -o main.o
View the symbols:
nm main.o
You can see that add is an undefined symbol.
This does not mean the compilation failed, because it may be defined in another object file or library.
If you link only main.o:
gcc main.o -o app
you may get:
undefined reference to `add'
because the linker cannot find the definition of add.
4. What is relocation?
At compile time, an object file usually does not yet know the addresses that the final code and data will have in the executable file.
For example:
extern int global_value;
int get_value(void) {
return global_value;
}
When the compiler generates machine code, it needs to reference global_value at some location.
But the final address can only be determined at the linking stage or the loading stage.
Therefore, the object file records relocation information.
Relocation is the process of fixing the positions in code or data that need adjustment, based on the final addresses of symbols.
Relocation information usually includes:
- The location that needs to be modified.
- The symbol being referenced.
- The relocation type.
- Any necessary additional calculation information.
5. Schematic of the Linking Process
flowchart TD
A["main.o"] --> D["Linker"]
B["math.o"] --> D
C["libc and other libraries"] --> D
D --> E["Read symbol table"]
E --> F["Resolve external symbols"]
F --> G["Merge sections"]
G --> H["Process relocations"]
H --> I["Generate executable file"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style I fill:#F1F3F5,stroke:#C9D0D8,color:#334155
VIII. Static Linking and Dynamic Linking
Linking can be performed using methods such as static linking or dynamic linking.
The most important difference between the two is whether library code is incorporated into the final program during the build stage.
1. Static Linking
Static linking typically copies or incorporates the library object code required by the program into the final executable file.
For example:
gcc main.c -static -o app
Whether this succeeds depends on whether the system provides the corresponding static libraries.
Characteristics of static linking:
- It can reduce runtime dependence on the corresponding dynamic libraries.
- The executable file is usually larger.
- Updating a library usually requires rebuilding the program.
- It may increase storage costs because multiple programs carry duplicate library code.
2. Dynamic Linking
Dynamic linking does not copy all shared library code into the executable file.
A program usually records its dependencies on shared libraries, and at runtime the dynamic linker loads the required libraries.
For example:
gcc main.c -o app
On Linux, you can view dynamic dependencies:
ldd ./app
The output may include:
linux-vdso.so.1
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
/lib64/ld-linux-x86-64.so.2
The specific paths and library versions depend on the system environment.
3. Comparison of Static and Dynamic Linking
| Aspect | Static Linking | Dynamic Linking |
|---|---|---|
| Library code | Included in the executable file | Shared libraries loaded at runtime |
| File size | Usually larger | Usually smaller |
| Runtime dependencies | Fewer dependencies on corresponding libraries | Requires compatible shared libraries |
| Library updates | Usually requires rebuilding | Shared libraries can be updated independently |
| Sharing across multiple programs | Usually carries duplicate code | Can share the same library mapping |
| Deployment | Simpler dependencies, but system limitations still apply | Requires managing dynamic library dependencies |
4. Runtime Process of Dynamic Linking
flowchart TD
A["Start the executable"] --> B["Operating system recognizes ELF"]
B --> C["Start the dynamic linker"]
C --> D["Find dependent shared libraries"]
D --> E["Map shared libraries"]
E --> F["Resolve dynamic symbols"]
F --> G["Perform necessary relocations"]
G --> H["Complete runtime initialization"]
H --> I["Enter program entry point"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style I fill:#F1F3F5,stroke:#C9D0D8,color:#334155
5. Lazy Binding and PLT/GOT
In the ELF dynamic linking mechanism, PLT and GOT are commonly used to handle dynamic function calls.
- PLT: Procedure Linkage Table.
- GOT: Global Offset Table.
They help the program locate function and data addresses in dynamic libraries at runtime.
In configurations that support lazy binding, some function symbols can be resolved only on their first call.
Basic process:
sequenceDiagram
participant App as Application
participant PLT as PLT
participant GOT as GOT
participant Loader as Dynamic Linker
participant Lib as Shared Library Function
App->>PLT: Call external function
PLT->>GOT: Query function address
GOT-->>PLT: Return initial resolution entry
PLT->>Loader: Request symbol resolution
Loader->>Loader: Find shared library and symbol
Loader->>GOT: Update function address
Loader-->>PLT: Return real address
PLT->>Lib: Jump to target function
Lib-->>App: Return execution result
The exact behavior is affected by linker parameters, runtime environment, and security configuration. For example, when immediate binding is enabled, some symbols are resolved in advance during program startup.
IX. Fifth Stage: Generating the Executable File
After linking is complete, the linker generates an executable file that the operating system can recognize.
On Linux, the common format is ELF.
On Windows, the common format is PE.
On macOS, the common format is Mach-O.
1. What Is an Executable File?
An executable file contains not only machine instructions but also the information the operating system needs to load the program.
Taking ELF as an example, it mainly contains:
- ELF file header.
- Program header table.
- Code and data contents.
- Dynamic linking information.
- Symbol and relocation information.
- Entry point address.
- Necessary runtime metadata.
2. ELF File Header
The ELF Header describes the basic attributes of the file.
For example:
- File type.
- Target architecture.
- Byte order.
- ELF version.
- Program entry point address.
- Program header table location.
- Section header table location.
View the ELF file header:
readelf -h app
In the output, pay attention to:
Class:
Data:
Type:
Machine:
Entry point address:
Where:
Class: 32-bit or 64-bit ELF.Data: byte order.Type: executable file, shared object, relocatable file, etc.Machine: target machine architecture.Entry point address: program entry point address.
3. Program Entry Point and main Function
Many beginners think that after the program starts, the CPU directly executes the main function.
In fact, in common C runtime environments, the program usually first enters the runtime startup code, then the startup code performs the necessary initialization, and finally calls main.
In Linux ELF programs, the entry point address usually points to the startup code rather than directly to main.
You can use:
readelf -h app
to view the entry point address.
Then use:
readelf -s app
Inspect the main symbol in the symbol table.
4. From the Entry Function to main
A typical C program startup process can be summarized as:
flowchart TD
A["Operating system creates the process"] --> B["Map the executable file"]
B --> C["Prepare the initial stack and runtime environment"]
C --> D["Jump to the program entry point"]
D --> E["C runtime startup code"]
E --> F["Run initialization logic"]
F --> G["Call the main function"]
G --> H["Execute the application"]
H --> I["Return or exit the process"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style I fill:#F1F3F5,stroke:#C9D0D8,color:#334155
The startup details are affected by the operating system, ABI, C runtime library, and linking method.
10. How Is a Program Loaded by the Operating System?
Once an executable file has been produced, it still needs to be loaded by the operating system before it can become a running process.
On Linux, executing a program usually involves the execve system call.
1. What Is Program Loading?
Program loading is the process by which the operating system maps an executable file into the process's virtual address space and prepares the execution environment.
The main tasks include:
- Checking the executable file format.
- Creating the process address space.
- Mapping the program's code and data.
- Setting up the user stack.
- Preparing command-line arguments and environment variables.
- Loading the dynamic linker.
- Completing the necessary runtime initialization.
- Setting the initial instruction execution location.
2. The Process Virtual Address Space
Once a program is running, it has its own virtual address space.
A typical layout includes:
| Region | Main purpose |
|---|---|
| Text | Program machine instructions |
| Data | Initialized global and static data |
| BSS | Zero-initialized global and static data |
| Heap | Dynamic memory allocation |
| Memory Mapping | Shared library and file mapping regions |
| Stack | Function calls, local variables, and so on |
The exact layout depends on the operating system, architecture, address space randomization, and the program's runtime state.
flowchart TB
A["High addresses"]
B["Process stack"]
C["Memory-mapped region"]
D["Heap"]
E["BSS"]
F["Data"]
G["Text"]
H["Low addresses"]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
G --> H
style A fill:#F1F3F5,stroke:#C9D0D8,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#F1F3F5,stroke:#C9D0D8,color:#334155
Note that this is only a conceptual layout diagram; it does not represent a fixed address ordering or specific address ranges for all processes.
3. Virtual Memory and Physical Memory
Programs use virtual addresses rather than operating directly on physical memory addresses.
The CPU's MMU (Memory Management Unit) is responsible for address translation.
The operating system uses page tables to establish the mapping between virtual pages and physical pages.
Therefore, a given virtual address in a program may ultimately correspond to:
- A physical memory page.
- A file mapping region.
- A shared memory region.
- A demand-mapped region for which no physical page has been allocated yet.
4. Demand Paging
The operating system usually does not copy the entire contents of the executable file into physical memory at startup.
Many pages use an on-demand loading mechanism.
When a program accesses a page for the first time that has not yet been backed by a physical mapping, a page fault may be triggered.
The operating system then establishes the mapping based on the page type or reads the content from a file.