Thuffir
Thuffir

Reputation: 89

C++ Memory Address of const class instances

I am using GCC 6.3.1 for ARM on CORTEX-M4 with -O2.

If I have a simple class instance like this:

class Test
{
  public:
    void Print(void) const
    {
      printf("Test");
    }
};
const static Test test;

and somewhere I refer the address of that object like:

printf("Address: %X", &test);

then I can see in the map file that the compiler reserves one byte for that address in the .bss segment:

.bss._ZL4test 0x20005308 0x1

Reserving one byte is logical since each object that is addressed must have an address. On the other side I would assume that for something simple like this the compiler would reserve space in the .text segment which does not cost any RAM space.

Now I could force the object into the .text segment by changing the definition to:

const static Test test __attribute__ ((section (".text")));

But then it is ALWAYS forced into that segment. This means the object will not work anymore when someone inserts a non const member variable.

Is there any way to tell g++ to put the address of such objects (without any member variables) into the FLASH instead of RAM (without using __attribute__)?

Upvotes: 6

Views: 353

Answers (1)

geza
geza

Reputation: 29962

If you have a constexpr constructor, and the created object is const, then GCC will put the object into the .rodata section automatically.

Upvotes: 5

Related Questions