If multiple target files contain definitions with the same name as the global symbol, the duplicate definition error will occur when these target files are linked.
For example, if we define a global integer variable in both the target file a and the target file B and initialize them, the linker will
When you connect to B, an error is reported.
This symbol can be defined as a strong symbol (strong symbol ). Some symbols can be defined as weak symbol ).
For C/C ++, the default function of the compiler and the initialized global variables are strong symbols, and uninitialized global variables are weak symbols.
You can use GCC's "_ attribute _ (weak)" to define any strong symbol as a weak symbol.
Both strong and weak symbols are for definition, not for symbol reference.
1 extern int ext;
2
3 int weak;
4 int strong = 1;
5 _ attribute _ (weak) int weak2 = 2;
6
7 int main (void)
8 {
9 return 0;
10}
In the previous program, "weak" and "weak2" are weak symbols. "strong" and "Main" are both strong symbols, while "Ext" is neither weak nor strong, because it is
Reference of an external variable (both strong and weak symbols are for definition ).
In terms of strength, the linker processes and selects the global symbols that have been defined multiple times according to the following rules:
(1) a strong symbol cannot be defined multiple times (that is, different target files cannot have the same strong symbol). If multiple strong symbol definitions exist, the linker reports a duplicate definition error.
(2) If a symbol is a strong symbol in a target file and is weak in other files, select a strong symbol.
(3) If a symbol is weak in all target files, select the one with the largest space occupied. For example, the global variable of the target file a is int type,
The destination file B is defined as the double type, which occupies 8 bytes. After the and B links to the destination file, the symbol global occupies 8 bytes (do not use multiple
Weak symbols of different types; otherwise, program errors that are hard to be found may occur ).