Search code examples
cmemorygccconstantsstorage-class-specifier

Is global const pointer to const data guaranteed to be placed in separate read-only section by gcc compiler in c/c++?


Given following definition of global (or static local) variable:

static const <type>* const ptr = {&var1, &var2, ...};

, may I rely upon the fact that both ptr and data in initializer list will be placed to separate read-only section of generated object file (i.e. it will not be placed to .data or similar sections containing non-const variables) ?

Question relates only to gcc c/c++ compiler behavior common to all architectures/platforms (at least those of them where read-only memory exists). It doesn't imply any platform, processor, OS, linker, start-up runtime, libraries, etc.

Please, don't ask me what I'm going to do. I know what I'm doing. If the information I provided are not enough for answer then issue has to be considered as xxx-specific and generic answer is "No". I have already read questions-answers where this subject was mentioned very close:

Impact of the type qualifiers on storage locations
How is read-only memory implemented in C?
Does "const" just mean read-only or something more?
Why does compiler allow you to "write" a const variable here?
GCC C++ (ARM) and const pointer to struct field
memcpy with destination pointer to const data

But I didn't found assured and direct answer.


Solution

  • According to the stackoverflow thread Where are constant variables stored in C? It is implementations specific. And personally I would not even rely on the thought that all GCC ports are implemented the same way. That's why for example the AVR port introduced a "progmem" attribute.

    So according to your

    Don't ask me what I'm doing, if there is not enough information, the answer is "no"

    attitude, I'd say here: The answer is "no" there is no portable way to guarantee something like that. In fact even if you instruct the compiler and the linker to place it in something like a "readonly section". If this section lies in RAM, who will prevent write access to this section?