Error "duplicate definition" when compiling two C files that reference the same header file

I have two C files and one header that look like this:

Header file header.h:

char c = 0; 

file1.c:

 #include "header.h" 

file2.c:

 #include "header.h" 

When compiling, I was warned about "duplicate definitions." I understand the reason, since the variable c is defined twice in the files file1.c and file2.c; however, I need to reference header.h in both c files. How do I solve this problem?

+4
source share
4 answers

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

Title:

 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 lead to a different program than using extern , as in the example above, so be careful. If you make it static , each file containing the header will receive its own copy of c . If you use extern , they will use one copy.

Secondly, use protection against double inclusion:

 #ifndef HEADER_H #define HEADER_H ... header file contents ... #endif 
+14
source

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

+3
source

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

0
source

If you cannot change the header, then as a hack in one (but not both) of the source files, you can do this:

 #define cd #include "header.h" 

This will cause char c = 0; will become char d = 0; but, of course, in another place where c used, it will also become d , so it may not work at all.

0
source

Source: https://habr.com/ru/post/1304314/


All Articles