简体   繁体   中英

a function that can declare global variables

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.

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM