2

It's been ages since I last worked with C++.

Situation: I have a large array that needs to be available in different .cpp files. It is immutable, so I thought I better put a const char array[] = … in the header file. But now the array appears several times in the compiled binary, as far as I can see.

What is the proper way to declare large constant arrays in a header, so they won't be compiled into every source object?

1
  • 3
    There are many duplicates here on SO. If you're too lazy to look for them the solution is to declare it in the header file and define it in a single source file. Commented Feb 28, 2014 at 8:51

2 Answers 2

10

If you define an array in a header file (whether or not you initialise it), you will get lots of copies.

You want to declare it in the header:

extern const char array[];

and define it like this in your .c / .cpp file:

const char array[] = ... ;
Sign up to request clarification or add additional context in comments.

3 Comments

@Enigma, not it should not be made static. In C, static globals are not visible to other .c files, i.e. the linker will not match one .c files the included extern from the .h file with the definition in the .c file that actually has the array in.
My fault: msdn.microsoft.com/en-us/library/s1sb61xd.aspx: "By default, an object or variable that is defined outside all blocks has static duration and external linkage."
Defining a const without initializing it is an error. The important point here is that const objects (unlike other objects) implicitly have internal linkage.
-2

Use the header guard in header file. So it prevent from multiple declaration. eg.

#ifndef HEADER_H
#define HEADER_H
const char array[] = …
.
.
#endif //HEADER_H

2 Comments

Header guards only protects against multiple inclusion in the same translation unit, not against inclusion in multiple translation units.
This is incorrect. As the header is included by each .c / .cpp file, with or without the guard, you will get a copy of the array compiled with each .c / .cpp file.

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.