-1

I am working on a project in c++ that requires me to build a memory model of a variable size. I need to represent each memory cell as a global variable.

for example a memory of size 10000 should be a vector of 10000 global variables of type memory cell named as m0-m9999. (memory cell is a struct I defined). normally in c++ if I create a single global variable memory cell, I declare it as extern memory_cell m0 in a common header file.

Is there a way to write a function that takes the size of the memory model and would make this declaration for me instead of me having to write the above line 10000 times?

sorry and perhaps thanks in advance.

hany erfan
  • 95
  • 7
  • A function? functions cannot be used for declarations, just for initizations of declarations. if you really insist on accessing the variables by different identifiers instead of choosing the correct one via index operator, you'll need to mention every declaration separately. You may be able to reduce the amount of code you need to write by using preprocessor macros, but this after the preprocessor is done the compiler will still effectively see `extern memory_cell m0; ... extern memory_cell m9999;` I definetly recommend using an array here: `extern std::array m;` – fabian Aug 15 '21 at 11:56

1 Answers1

1

You could use something like this. Also see : How to implement multithread safe singleton in C++11 without using <mutex>

header file memorycells.h #include

struct memory_cell
{
};

static std::vector<memory_cell>& cells()
{
    static std::vector<memory_cell> cells(100000);
    return cells;
}

source file #include "memory_cells.h"

main()
{
    memory_cell = cells()[42];
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • 1
    `main()` must be `int main()`. I'd make the vector a plain global variable, unless it needs to be accessed before `main` is entered. – HolyBlackCat Aug 15 '21 at 11:45
  • You are right on both accounts, I tend to use this construct since the cells can also be accessed from other source files if needed. – Pepijn Kramer Aug 15 '21 at 11:48
  • You don't need a function to allow access from other files. You can just declare the variable as `extern` in a header. The function is only needed if the object must be created on first access, e.g. because it's accessed very early, before `main` is entered and before it would be constructed otherwise. – HolyBlackCat Aug 15 '21 at 11:49