I see these linking rules somewhere (including CSAPP), saying that:
- When there is multiple strong symbols, linking failed;
- When there is strong symbol and weak symbol with the same name, linker choose the strong one;
- When there is only multiple weak symbols, linker choose one randomly;
Supposing these rules are true, I did this:
// main.cpp#include <stdio.h>int gvar;int main(){ printf("shared var is %d\n",gvar); return 0;}// aux.cppint gvar = 111;
gcc -o test main.cpp aux.cpp/usr/bin/ld: /tmp/ccQq1mwo.o:(.data+0x0): multiple definition of `gvar'; /tmp/ccgMcACl.o:(.bss+0x0): first defined herecollect2: error: ld returned 1 exit status
Why this error occur?
And I found that if I change "main.cpp" and "aux.cpp" to "main.c" and "aux.c", this error just disappears! Why?
By the way, my gcc version is 8.4.0.