0

I see these linking rules somewhere (including CSAPP), saying that:

  1. When there is multiple strong symbols, linking failed;
  2. When there is strong symbol and weak symbol with the same name, linker choose the strong one;
  3. 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.cpp
int 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 here
collect2: 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.

  • Does https://stackoverflow.com/questions/1490693/tentative-definitions-in-c-and-linking with "there was never such extension in C++ langauge" answer your question? – KamilCuk Jun 19 '22 at 09:39
  • 1
    https://stackoverflow.com/questions/2026217/difference-in-linkage-between-c-and-c – Mat Jun 19 '22 at 09:39
  • You might want to also read [Definitions and ODR (One Definition Rule)](https://en.cppreference.com/w/cpp/language/definition) _"...One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the __entire program__ ...The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined...."_ – Richard Critten Jun 19 '22 at 09:43

0 Answers0