0

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.

broken.eggshell
  • 945
  • 7
  • 13
  • Without `extern`, each compilation unit including the header has a different `int x`. – Arkku Sep 19 '22 at 23:36
  • It depends upon the compiler [and its version]. For many years, `gcc` [and other compilers] defaulted to `-fcommon`. But, `gcc` starting with version 12.x.x(?) defaults to `-fno-common` See my answer: [Global variables and the .data section](https://stackoverflow.com/a/64627070/5382650) The TL;DR: Just add `-fcommon` to the command line. – Craig Estey Sep 19 '22 at 23:40
  • Yes, the code without `extern` is incorrect. For largely historical reasons, however, some compilers will accept it. But note well that the code *with* `extern` is also incorrect, unless there is also a *bona fide* definition of `x` somewhere else. – John Bollinger Sep 19 '22 at 23:48
  • I think I now have a better understanding of the extern keyword, and I can see that the compiler plays a big role in terms of how it is implemented. – broken.eggshell Sep 20 '22 at 01:40

0 Answers0