Error 'duplicate definition' when compiling two C files that reference one header file

c, definition, header

Solution

First, don't define variables in headers. Use the `extern` qualifier when declaring the variable in the header file, and define it in one (not both) of your C files or in its own new file if you prefer.

header:

extern char c;

implementation:

#include <header.h>
char c = 0;

Alternatively, you can leave the definition in the header but add `static`. Using `static` will cause different program behaviour than using `extern` as in the example above - so be careful. If you make it `static`, each file that includes the header will get its own copy of `c`. If you use `extern`, they'll share one copy.

Second, use a guard against double inclusion:

#ifndef HEADER_H
#define HEADER_H

... header file contents ...

#endif

Problem

I have two C files and one header that are as follows: Header file header.h: ``` char c = 0; ``` file1.c: ``` #include "header.h" ``` file2.c: ``` #include "header.h" ``` I was warned about 'duplicate definition' when compiling. I understand the cause as the variable c is defined twice in both file1.c and file2.c; however, I do need to reference the header.h in both c files. How should I overcome this issue?

Original source