super newbie
super newbie

Reputation: 61

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

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?

Upvotes: 6

Views: 23780

Answers (4)

Giuseppe Guerrini
Giuseppe Guerrini

Reputation: 4428

Use extern char c in your header, and char c = 0 in one of your .c files.

Upvotes: 4

dreamlax
dreamlax

Reputation: 95335

If you can't modify the header, then as a hack, in one (but not both) of your source files, you could do this:

#define c d
#include "header.h"

This will result in char c = 0; becoming char d = 0;, but of course, anywhere else that c is used, it will also become d, so it may not work at all.

Upvotes: 0

Earlz
Earlz

Reputation: 63835

What is char c used for? You probably want it to be extern char c or if you want for this to be a separate variable for each compilation unit(source file) then you should use static char c

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224964

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

Upvotes: 16

Related Questions