I have written a small C library that I am trying to compile to a shared object. When compiling on my Mac, where gcc links to clang, the code compiles just fine with or without the extern
keyword. When I compile on Linux, I get an error unless I include the extern
.
Here is a MWE:
include/common.h
#ifndef _COMMON_H_
#define _COMMON_H_
extern int x; /* Omitting extern causes error on Linux */
#endif
include/sample.h
#ifndef _SAMPLE_H_
#define _SAMPLE_H_
#include "common.h"
#endif
src/common.c
#include "common.h"
src/sample.c
#include "sample.h"
Compile with:
gcc -c -Iinclude -fPIC src/*
gcc *.o -shared -o libsample.so
This is the error on Linux:
/usr/bin/ld: build/common.o:(.bss+0x0): multiple definition of `x'; build/category.o:(.bss+0x0): first defined here
I googled a bit, but I'm still not sure what is happening here. Is the code without the extern
incorrect, or is there some issue with the compiler? Or is there some difference in what -fPIC
does on Mac vs. Linux? I've only dabbled in C, but I don't recall ever needing to declare global variables as extern before.