Search code examples
cgcclinaro

Why gcc place a large constant array to ".rwdata" section rather than ".rodata" section?


/* 0xFFFFFFFF * 256*/
#define test_256X0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, ... 0xFFFFFFFF

After compiling, the const array is placed in ".rwdata" section rather than ".rodata" section, and I don't know why.

After google and searching the stackoverflow site, there is no specified answer. Does anyone know why or how to ask the compiler (or linker) to output a warning message when "placing constant data into non-read-only section"? thanks.

PS. I resolve my problem by adding __attribute__((section(".rodata")))

__attribute__((section(".rodata"))) volatile const int TEST_ro[512] = {test_256X, test_256X};

PS. I use linaro-gcc compiler for ARM core


Solution

  • Answer: If I want a variable to be "volatile" and placed in read-only section, use

    __attribute__((section(".rodata"))) /* default read-only data section*/
    

    is the best way.

    reference:

    1. That's not what volatile is for. It indicates to the compiler that the memory may be changed asynchronously so it doesn't used cached results. It's inconsistent with const. Try static which tells the compiler that other modules cannot access it.

    2. If you want to place a variable in a specific section, then using the explicit section placement is the way to go. The C standard gives a very limited set of tools for this, so you are at the mercy of what the compiler provides. __attribute__ is not pretty, but it's most likely what you need to do.