ELF文件中.data段与.symtab段的区别是什么?
Great question—this is such a common mix-up when you start digging into how compilers and linkers put programs together. Let’s break this down clearly:
This is the section that actually holds the values your program uses when it runs. Here’s what you need to know:
- It’s loaded into your program’s memory at runtime—when the OS launches your executable, it copies the contents of .data into the process’s address space so your code can read and write to these values directly.
- It stores initialized global variables and static variables—think code like
int global_counter = 10;orstatic char greeting[] = "hello";. The actual binary values (10, the ASCII bytes for "hello") live here. - Its size is fixed at compile time, based on the total size of all initialized variables you’ve defined.
- This section is critical for your program to run correctly—without it, your initialized globals would have no place to live.
This is totally different—it’s a metadata section, not actual program data. Here’s the lowdown:
- It’s not loaded into memory when your program runs (unless you compile with full debug symbols and keep them in the executable). It’s only used during linking and debugging.
- It stores information about symbols—things like the names of global variables, their memory addresses (or offsets in sections like .data), function names, types, and sizes. For that
global_countervariable, .symtab would have an entry that says: "Name: global_counter, Type: int, Size: 4 bytes, Location: offset 0 in .data section". - Its job is to help tools like the linker (which stitches together multiple object files) and debuggers (like gdb) do their work. The linker uses .symtab to find where symbols live across files, and debuggers use it to translate raw memory addresses back into human-readable names you recognize.
- You can even strip the .symtab from an executable with the
stripcommand, and your program will still run perfectly fine—you just lose the ability to debug it easily or do certain linking tasks.
- Purpose: .data holds runtime values; .symtab holds metadata for tools.
- Runtime Presence: .data is in your process’s memory; .symtab stays on disk (usually).
- Content: .data stores binary values; .symtab stores symbol names, addresses, and attributes.
- Mandatory: .data is required if you have initialized globals; .symtab is optional for execution.
To put it simply: .data is where your variables’ actual values live, like a storage closet for your program’s data. .symtab is like a map or directory that tells tools where those variables are and what they’re called—you don’t need the map to use the closet, but it makes finding things way easier.
内容的提问来源于stack exchange,提问作者Lenny

