Reputation: 409
I have a header file and two source files. In said header file I have the following declaration:
const char *letters[] = {"A", "B", "C", "D"};
I have included my header file in both source files. When I try to compile I get:
/tmp/cc6gLw9s.o:(.data+0xa0): multiple definition of `letters'
/tmp/ccjqd0rr.o:(.data+0xa0): first defined here
Upvotes: 0
Views: 109
Reputation: 8129
In addition to @Schwern's answer, you can also do this:
#pragma once
const char *letters[] = {"A", "B", "C", "D"};
Note that #pragma once
isn't standard C, but it is supported on most compilers.
Upvotes: 0
Reputation: 164769
Including a file in C is almost literally copying and pasting it. If a header is included twice in the same compilation it will be as if that code was written twice.
This is usually avoided by using the pre-processor to prevent the header from being compiled twice.
#ifndef _MYHEADERS_H_
#define _MYHEADERS_H_
const char *letters[] = {"A", "B", "C", "D"};
#endif
This is in addition to the issues brought up in the other answers.
Upvotes: 1
Reputation:
If you compile the 2 source files separately and each of them includes the header, then the variable letters
will be declared twice, once in each source file. To prevent this, declare the variable as extern
in the header file.
extern const char *letters[];
Then, put the actual variable in 1 source file.
const char *letters[] = {...};
Upvotes: 5