Reputation:
I believe my question is different to this one. Here I am asking why we need to differentiate those two, the link only answer which one goes to which.
We know that:
Common section is for uninitialized global variables and
Bss section is for uninitialized static variables plus global variable initialized to 0.
But why differentiate BSS and COMMON section? Especially for global variables initialized to 0, can't we put them in .data section which is for initialized global variables? Isn't that initialize a variable to 0 is also a initialization?
Below is an explanation from my textbook:
in some cases the linker allows multiple modules to define global symbols with the same name. When the compiler is translating some module and encounters a weak global symbol, say, x, it does not know if other modules also define x, and if so, it cannot predict which of the multiple instances of x the linker might choose. So the compiler defers the decision to the linker by assigning x to COMMON. On the other hand, if x is initialized to zero, then it is a strong symbol, so the compiler can confidently assign it to bss.
I am really confused, it says “it does not know if other modules also define x”, but how can you define a variable twice? Is an example code available to illustrate?
Upvotes: 0
Views: 1202
Reputation: 21916
.bss
section is used for allocating zero-initialized data for optimization purposes, to allow
memset
ing memory at startup.Common section is used (on some platforms e.g. Windows but not ELF) to implement so called "common symbols" i.e. symbols which may be duplicated in different object files ("translation units"). When such symbol falls into a common section, static linker will merge all separate definitions (with some platform-specific rules, e.g. merge only if identical, prefer largest definition, etc.).
On some targets common sections are used only for uninitialized data (which make them somewhat similar to .bss
) and on others also for vague symbols. In general there are no logical reasons for why different platforms made different choices regarding usage of common sections, it's purely historical.
You can find some history behind common symbols in [Raymond Chen's article] (https://devblogs.microsoft.com/oldnewthing/20161024-00/?p=94575).
Upvotes: 3