views:

265

answers:

4

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?

+10  A: 

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
Carl Norum
+1  A: 

uset "extern char c" in your header, and "char c = 0" in one of your .c file

Regards

Giuseppe Guerrini
A: 

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

Earlz
A: 

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.

dreamlax