Reputation: 8313
I have a huge array that is written literally thanks to a script. It is basically an image file converted to an array.
I could define the body as a macro or put it into a const type in a header. If I did set it as a const, what will be the memory lifespan? Does it last for the entire program? Does it last for as long as the scope it's used in, like in a function? Would using macros be a better option?
Upvotes: 1
Views: 392
Reputation: 490108
I'd move the array definition into a source file (probably by itself):
// bitmap.cpp
char const my_bitmap[] = {
0x12, 0x34, 0x56, // lots of data here...
};
Then write a header that just has an extern declaration for it:
//bitmap.h
extern char const my_bitmap[];
This gives all code (that includes the header) access to the data, but assures that you only have one copy of the data for everybody to use. It also avoids pointlessly re-compiling the code that represents the bitmap, once for each file that needs access to the data.
Upvotes: 9
Reputation: 229088
If the array is defined in a header file, that array will have global scope, and it will live as long as the application lasts.
Note, if you include that header multiple times,you'll likely get a linker error stating you have the same symbol/name several places. If the array is static, you'll have a copy of that array in every source file that includes that header.
If you defined the array as a macro, it'll live according to where you use that macro, and you will get a copy of the array every place you use that macro - doesn't sound like a good solution in all but the simple cases where the array is quite small.
Upvotes: 2