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?
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
Use extern char c in your header, and char c = 0 in one of your .c files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With