Object files
- C course
- Expert
- Lesson 31/47
- 5 min
Learn the structure of object files (.o).
What is an object file?
An object file (.o) is the relocatable machine code the compiler produces from a source file. It is not yet executable; the linker combines several object files into the final executable.
An object file has three main sections: .text (machine instructions), .data (initialized global variables) and .bss (uninitialized global variables). Each section is written with relative addresses; the linker assigns final addresses later. The object file also contains a symbol table and relocation entries; these let the linker do its job.
Object file sections
The sections of an object file hold different kinds of content. The .text section contains machine instructions; it is usually read-only. The .data section holds initialized global variables; for example int counter = 42; goes here.
The .bss section holds uninitialized or zero-initialized variables; for example int total;. BSS takes no space in the file; only its size is recorded. This split lets the linker and loader place each section in the right memory region. Sections are standardized in file formats such as ELF.
Practice Object file simulation
Define the global int counter = 42; (this goes to .data). Write int get_counter(void) that returns counter (this goes to .text). Write int main(void) and print with printf("Sayaç: %d\n", get_counter()).
Starter code
#include <stdio.h>
// genel sayaç tanımla
// get_counter fonksiyonu yaz
// main'de değeri yazdırSample solution
#include <stdio.h>
int counter = 42;
int get_counter(void) {
return counter;
}
int main(void) {
printf("Sayaç: %d\n", get_counter());
return 0;
}Expected output
Sayaç: 42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a .o file contain?
- Only source code
- An executable binary
- Relocatable machine code Correct answer
- Just plain text
Explanation: A .o file is relocatable code the linker will combine.
2 Complete the section name
int counter = 42; /* .____ bölümünde */
int counter = 42; /* .data bölümünde */
Explanation: Initialized global variables go in .data.
3 Match section to content
| Term | Meaning |
|---|---|
text |
Machine instructions |
data |
Initialized data |
bss |
Uninitialized data |
rodata |
Read-only constant |