咨询:C语言中引入的库在地址空间中的存放位置
Great question—this is one of those details that’s easy to gloss over but makes a big difference when you’re debugging or optimizing your code! The answer depends on whether you’re using static libraries or dynamic libraries—let’s break it down:
静态库(Static Libraries)
When you link a static library (like .a files on Linux or .lib on Windows) to your C program, the linker does a full merge at compile time:
- The library’s function code gets folded directly into your program’s code (text) segment, right alongside your own hand-written functions.
- Any global variables or
staticvariables in the static library are merged into your program’s data segment (if initialized) or bss segment (if uninitialized, zero-initialized by default).
Once the executable is built, the static library’s code and data are indistinguishable from your program’s own—there’s no separate "library region" at runtime; it’s all part of the same address space blocks you already know.
动态库(Dynamic Libraries)
Dynamic libraries (like .so files on Linux or .dll on Windows) work differently—they’re loaded at runtime when your program starts (or even later, if you use dlopen() on Linux). Here’s how they fit into the address space:
- The library’s code is loaded into a separate, dedicated read-only segment in your process’s address space. This segment is shared across all processes that use the same dynamic library (so the OS only keeps one copy of the code in memory, saving resources).
- The library’s data (global variables,
staticvariables) gets loaded into a writable segment that’s unique to your process. This uses a copy-on-write mechanism—if your process modifies these variables, it gets its own private copy instead of altering the shared library data.
Unlike static libraries, dynamic libraries live in their own distinct regions of the address space, but they’re still part of your process’s overall address space layout.
To wrap it up: Static libraries become part of your program’s existing code/data segments, while dynamic libraries get loaded into their own dedicated (and often shared) segments at runtime.
内容的提问来源于stack exchange,提问作者iceQueem

