Strong symbol, a weak symbol

Verbatim https://www.dazhuanlan.com/2019/08/26/5d6304ae4bca7/


For the linker, all the global symbols can be divided into two types: strong symbol (Strong symbols), weak symbol (Weak symbols). The attribute has a gcc attribute ((weak)), this symbol is used to declare a weak symbol. gcc manual wrote:

Of The weak attribute Causes The Declaration to BE Emitted AS A weak Symbol Rather Within last A Global. This IS the Primarily Useful in Defining Library Functions Which CAN BE Overridden in User code, though IT CAN Also BE Used with non-function Declarations. Weak Symbols are Supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.
for this gcc extension, here we made a simple introduction. Let's look at the more general case. ;)

In general, functions and variables are initialized strong symbol uninitialized variables is weak symbol. For them, the following three rules apply:

1. Strong symbol of the same name can be only one.
2. There is a strong and weak symbols of the same name are possible, but the definition may choose strong symbol.
3. When a plurality of weak symbol, the linker can select any one.

Three rules seem well understood, it is not true, especially when these types of weak symbols and symbols are not strong at the same time! Seemingly the correct process can lead to serious errors! Consider the following csapp in example:

===a.c===
int x=7;
int y=5;
p1() {}

===b.c===
double x;
p2() {}

We compile them together, and p2 () function assigned to x, you will find, y also changed! Although x is seen as double, but it will take ac defined in int x, that is to say, int x bc of the ac will double in when to use! This of course is wrong! The reason for this is because the above rule 2. One way to avoid this problem is to add gcc -fno-common options.

On Weak symbol, man explained to the manual:

Guess you like

Origin www.cnblogs.com/petewell/p/11410486.html