Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
super newbie Avatar asked Mar 16 '10 21:03

super newbie


2 Answers

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
like image 119
Carl Norum Avatar answered Nov 15 '22 05:11

Carl Norum


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

like image 39
Giuseppe Guerrini Avatar answered Nov 15 '22 05:11

Giuseppe Guerrini