Reputation: 13020
If I define a large constant string in a header file that is included multiple times, will it create multiple copies of the constant string in the executable? (If it does, is there a way to avoid this without needing a separate source file?)
This is what the header looks like:
#pragma once
// this is generated by a tool, so keeping it in one header makes life easy
const uint32 TABLE_SIZE = 65536;
const uint8 TABLE[TABLE_SIZE] = {...};
Upvotes: 0
Views: 614
Reputation: 38834
In C++, a const variable defined at file scope has internal linkage only, i.e. it's only visible in that translation unit. Defining it in a header file should therefore not cause any errors about multiple definitions.
Thus each include will produce new copy of the buffer.
Sometimes you can prevent it for example in MSVC for const strings with the option /GS
. But it will be not working for char array initializers like yours, it is for const char* p = ...
only.
If it does, is there a way to avoid this without needing a separate source file?
No, there is not.
Upvotes: 0
Reputation: 13020
Looked into how stb_image.h handles it's header-only implementation and found a workable way to include the large string only once in the executable:
The header now looks like this:
#pragma once
// #define IMPLEMENT_TABLE in one and only one cpp file
// before including this header to define the table
const uint32 TABLE_SIZE = 65536;
extern const uint8 TABLE[TABLE_SIZE];
#ifdef IMPLEMENT_TABLE
const uint8 TABLE[TABLE_SIZE] = {...};
#endif
Upvotes: 0