user2549327
user2549327

Reputation:

dynamically reference header variables c++

I know that C++ cannot create variables at runtime. Everything has to be declared when it is compiled.

My question is, if I have, let's say, 10 included header files with simple variable names, can I reference them dynamically, by the header file name or something like that.

For example, if I had two header files, one called "myVars1.h" with variable "myVars1name" and another called "myVars2.h" with a variable "myVars2name" could I do something like

int fileNum = 1;
string name = ["myVars" + fileNum + "name]; //i wish this worked...

Is this along the same lines as creating variables at runtime (and therefore illegal)?

Thanks

Upvotes: 0

Views: 403

Answers (2)

ROTOGG
ROTOGG

Reputation: 1136

Assuming these variables are declared in header files, and defined somewhere else as global variables, you may get what you want by using dlsym(). Basically C/C++ cannot define variables at runtime, but it can load them at run time.

Precondition: these variables must be built into shared library, e.g. mylib.so

....
int fileNum = 1;
string name = ["myVars" + fileNum + "name]; //i wish this worked...

void *handle = dlopen("$PATH/mylib.so", RTLD_LAZY);
void *varPtr = dlsym(handle, name);  // Your wish comes true here...
//cast varPtr to its target type.
....

Upvotes: 2

Evgeny Eltishev
Evgeny Eltishev

Reputation: 603

I think you should use Namespaces

Upvotes: 0

Related Questions