11 years, 4 months ago.

How to avoid multiple copies of a const in binary file?

I have some bitmaps stored in a header file as:

Bitmaps.h


#ifndef BITMAPS_H
#define BITMAPS_H

const unsigned char bitmap1[2888] = { ... };
const unsigned char bitmap2[2888] = { ... };
....

#endif

I include this header file in a number of libraries and I've found that multiple copies of the arrays are stored in the binary file. How can I define this bitmaps so that only one copy of each is found in the binary?

Thanks

3 Answers

11 years, 4 months ago.

You should not define your data arrays in the header file. You should only declare them in the header, and define the actual data in one (and only one) of the .cpp files.

Bitmaps.h

extern const unsigned char bitmap1[2888];

and

Bitmaps.cpp

const unsigned char bitmap1[2888] = { ... };

Check this for a complete example.

Accepted Answer

+1

posted by Martin Kojtal 09 May 2014

Thanks Igor. This has sorted it

posted by Tim Barry 12 May 2014
11 years, 4 months ago.

Libraries are independent pieces of code that are compiled separately and therefore they reserve space for constants as defined in your code. You could instead modify the lib to use a pointer to the constant data, then use a single constant table in your main (basically the bitmaps.h you have now) and provide those pointers as parameters when instantiating the objects in the library.

11 years, 4 months ago.

Are you sure? I just tried it with a simple .h file which was included by two others, which again were included by main.cpp, but the second one didn't do anything.

You can try adding #pragma once. But I wasn't able to test it since I don't seem to get the issue in the first place.