0

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
2
  • 4
    You have the same variable defined multiple times, it's an array but still a variable. You shouldn't put variable definitions in headers. Commented Mar 9, 2017 at 18:18
  • 3
    That is technically not a compiler error but a linker error, and means that you define the variable in multiple translation units (basically source file with all included headers). Don't define variables (or functions) in header files. Commented Mar 9, 2017 at 18:19

3 Answers 3

5

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[] = {...};
Sign up to request clarification or add additional context in comments.

3 Comments

Can you please add a sentence or two about why global variables, especially those with external linkage, are problematic? It's the only thing that bothers me about this answer.
I'm not really sure what to say about that. I get that they're ugly, but I haven't really had any experience with them being particular trouble in the past since I primarily use unity builds.
It's not so much about the build as much as it is about good design for encapsulation. It also becomes a nightmare in multi-threaded programs. But okay, NVM.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.