I have code that, when I compile on Linux, works fine, but fails on MinGW for Windows.
I'm compiling these four files together. a.h
is the header file, b.c
, c.c
and main.c
. Here are the contents.
└──> cat a.h
enum {
BLACK,
WHITE
} Colors;
└──> cat b.c
#include "a.h"
#include <stdio.h>
void foo() {
printf("%d\n", BLACK);
}
└──> cat c.c
#include "a.h"
#include <stdio.h>
void bar() {
printf("%d\n", WHITE);
}
└──> cat main.c
void foo();
void bar();
int main() {
foo();
bar();
return 0;
}
I compile them with this command:
gcc -c b.c; gcc -c c.c; gcc -c main.c; gcc -o colors b.o c.o main.o
It works fine on my Linux desktop but it fails on a MinGW VM. The error is:
# gcc -c b.c; gcc -c c.c; gcc -c main.c; gcc -o colors b.o c.o main.o
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: c.o:c.c:(.bss+0x0): multiple definition of `Colors'; b.o:b.c:(.bss+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
When I run nm
on b.o
on Linux, I see this:
└──> nm b.o
0000000000000004 C Colors
0000000000000000 T foo
U printf
But on MinGW, I see this:
0000000000000004 B Colors
Somehow gcc is compiling them differently on each system. The B
there means that I can't have the same symbol twice, though on Linux I get C
and it works fine. From the manpage for nm
:
"B"
"b" The symbol is in the uninitialized data section (known as BSS).
"C" The symbol is common. Common symbols are uninitialized data. When linking, multiple common symbols may appear with
the same name. If the symbol is defined anywhere, the common symbols are treated as undefined references.
How do I fix this so that I am able to compile on MinGW?
Linux uses GCC 9; MinGW probably uses GCC 10.