Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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__)?

like image 585
Thuffir Avatar asked Jul 30 '18 12:07

Thuffir


People also ask

What is a memory address in C programming?

When a variable is created in C, a memory address is assigned to the variable. The memory address is the location of where the variable is stored on the computer. When we assign a value to the variable, it is stored in this memory address.

What is static memory allocation in C?

1. Static Memory Allocation As we discussed static memory allocation is the allocation of memory for the data variables when the computer programs start. This type of allocation is applied to only global variables, file scope variables and also to those variables that are declared as static.

What is a typical memory representation of C program?

A typical memory representation of C program consists of following sections. 1. Text segment 2. Initialized data segment 3. Uninitialized data segment 4. Stack 5. Heap 1. Text Segment:

Can we take the address of a constant variable in C++?

Also in C, constants are not compile time constants(i.e always allocated storage), so you can safely take address of a constant variable.But in C++, if you take address of a constvariable it will not be a compile time constant and will be allocated storage. Edit


1 Answers

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

like image 171
geza Avatar answered Sep 22 '22 09:09

geza