'GCC, constant tables and .rodata

I have a strange problem with gcc and constants and .rodata

Let's assume:

typedef const struct {
   const char *a;
} data_t;

typedef const struct {
  const data_t d[2];
} bulk_data_t; 

Now if I have:

bulk_data_t bd[] = {
{{
 "Test1", "Test2"
}}
};

My struct goes to .rodata

However:

const char *test_const = "Test1";
const bulk_data_t bd[] = {
{{
 test_const, "Test2"
}}
};

My data will go to .data (problem is, it is not defined read only and the test_const is actually initialised by code).

It's compiled as C++ code because C standard does not allow defining char constants outside struct definition.

Any idea how to force gcc to make it into .rodata? Forcing it by adding attribute((section(".rodata"))) causes very strange outcomes at linker level.

Thanks and have a great day!



Solution 1:[1]

const char *test_const = "Test1"; defines a non-constant pointer to constant characters and initializes it with the address of a string literal, an unnamed array of constant characters.

To get what you want, you need to add another const to make the pointer constant, too:

const char * const test_const = "Test1";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 the busybee