Tony the Pony
Tony the Pony

Reputation: 41357

Arranging global/static objects sequentially in memory

In C++, is it possible to force the compiler to arrange a series of global or static objects in a sequential memory position? Or is this the default behavior? For example, if I write…

MyClass g_first (“first”);
MyClass g_second (“second”);
MyClass g_third (“third”);

… will these objects occupy a continuous chunk of memory, or is the compiler free to place them anywhere in the address space?

Upvotes: 2

Views: 560

Answers (3)

sbi
sbi

Reputation: 224069

The way to force objects to be in a contiguous piece of memory is to put them into an array.

If you use the built-in array type, the only way they can be initialized is their default constructors (although you can change their values later):

MyClass my_globals[3];

If you use a dynamic array (called std::vector in C++), you are more flexible:

namespace {
  typedef std::vector<MyClass> my_globals_type;

  my_globals_type init_my_globals()
  {
    my_globals_type globals;
    globals.push_back(MyClass(“first”));
    globals.push_back(MyClass(“second”));
    globals.push_back(MyClass(“third”));
    return globals;
  }

  my_globals_type my_globals = init_my_globals();
}

Note that global variables are usually frowned upon. And rightly so.

Upvotes: 0

Alphaneo
Alphaneo

Reputation: 12539

Placing specific variables or group of variables into a memory segment is not a standard feature of the compiler.

But some compiler supports special methods to do this. Especially in embedded systems. For example in Keil, I guess you at at operator to place a particular variable.

Upvotes: 0

Adam Maras
Adam Maras

Reputation: 26853

The compiler can do as it pleases when it comes to placing static objects in memory; if you want better control over how your globals are placed, you should consider writing a struct that encompasses all of them. That will guarantee that your objects will all be packed in a sequential and predictable order.

Upvotes: 3

Related Questions