symbol 的 definition 可分為 strong symbol 跟 weak symbol。C/C++ 的 compiler 預設 function 及有初始化的 global variable 為 strong symbol,未初始化的 global variable 為 weak symbol。strong & weak symbol 跟處理 symbol 重複定義有關:
GCC 中可用 __attribute__((weak)) 來定義一個 strong symbol 為 weak symbol:
weaksym.cpp
1
__attribute__((weak)) int x = 2; // weak symbol
main.cpp
1 2 3 4 5 6 7 8
#include<iostream>
int x = 123; // strong symbol
intmain(){ std::cout << x << endl; // result is 123 return0; }
weak symbol 可以在 link time 置換 function。一開始給個預設 implementation 並設為 weak symbol,使用者可以寫 function 編成 object file 去 link。由於使用者寫的是 strong symbol 會蓋掉原本的 default implementation,達到 link 階段換 implementation。