A weak symbol is a specially annotated symbol in ELF files. By default, a symbol is strong. During linking, a strong symbol can override a weak symbol with the same name. On the other hand, when two strong symbols by the same name are found during linking, the linker resolves the name to the first symbol.
When linking an executable, a weakly declared symbol doesn’t need a definition. On the other hand, the linker will throw an error for a strong undefined symbol.
Since the C and C++ standards don’t mention weak symbols, inserting them explicitly in the code is not very portable. Different platforms can have subtly different semantics.
GCC provides #pragma weak
and __attribute__((weak))
to declare weak symbols.
As annotated by nm
, a weak function with definition available is “W” whereas one without a defintion is “w”. Similarly, a weakly defined variable symbols are “V” and “v”.