When trying to compile and link two c modules with GCC, both containing a global variable with the same name, I get an error of multiple definitions. Despite the fact that both are so-called weak symbols.
A code example:
I've tried to compile and link the 2 following c modules:
// b1.c
int x;
int main() {}
// b2.c
int x;
Now, supposedly, the var x
in both files, should be a weak symbol.
So when linking, both should reference the same value.
But, for some reason, I get the following error:
$ gcc b1.c b2.c
/usr/bin/ld: /tmp/ccCP4DM3.o:(.bss+0x0): multiple definition of `x`; /tmp/ccN4Bd4O.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
$ gcc --version
gcc 11.3.0
$ ld --version
GNU ld 2.38
So, did something change? Because according to the "Computer Systems A Programmer’s Perspective" section 7.6, it should compile and link just fine using gcc without any special flags.