Here I have a small program:
// header.h
#pragma once
int a;
int reta();
// extra.c
#include "header.h"
int reta() {
return a;
}
// main.c
#include "header.h"
#include <stdio.h>
int main(void) {
printf("%d, %d", a, reta());
}
Result when compiling with Visual Studio (C standard: c17, Debug x64):
0, 0
Result when compiling with GCC (gcc -L. -o test.exe *.c -std=c17 -mwindows -Wl,-subsystem,console):
C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/13.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:...\Temp\ccGvFOtk.o:main.c:(.bss+0x0): multiple definition of `a'; C:...\Temp\ccANU1lv.o:extra.c:(.bss+0x0): first defined here collect2.exe: error: ld returned 1 exit status
My question: why is there a difference, and what should I do to fix the error in GCC case?
aChange header.h toextern int a;and do the definition in one of the C files.extern.externto share variables between source files?, especially the section on "Not so good way to define global variables". GCC 10.1 changed the rules to conform more accurately to the C standard, electing not to take the option allowed by Annex J as a 'common extension' by default. You are seeing a consequence of that decision.