Anne Quinn
Anne Quinn

Reputation: 13000

How to get global variable declared in Main.cpp to be accessible in a header

How would I get a global variable to appear in a header that's included after the variable's declaration? I have it arranged like this, but within the header, it's not recognized as being defined:

main.cpp:

const int COUNT = 10;
void (* FUNCTION[COUNT])();
const char * DESCRIPTION[COUNT];

#include "TestFont.h"

testFont.h:

#define COUNTER_VAR = __COUNTER__;
DESCRIPTION[COUNTER_VAR] = "description";
FUNCTION[COUNTER_VAR] = func;
#undef COUNTER_VAR

In the header, DESCRIPTION and FUNCTION are seen as undefined, how would I make it so they can be used?

Disclaimer: It's super ugly isn't it! This is strictly for a sandbox project in VS, so I can write small single-file tests or scripts in C++ with as little IDE setup ceremony as possible. The goal is to make it so all I need do is include the header in main.cpp, and main will have the necessary function pointer and description to list it as an option in the console. No grades please!

Upvotes: 1

Views: 196

Answers (1)

R Sahu
R Sahu

Reputation: 206607

The following lines are not legal outside of a function body.

DESCRIPTION[COUNTER_VAR] = "description";
FUNCTION[COUNTER_VAR] = func;

You may need to wrap that in a helper function.

static int init()
{
#define COUNTER_VAR = __COUNTER__;
   DESCRIPTION[COUNTER_VAR] = "description";
   FUNCTION[COUNTER_VAR] = func;
#undef COUNTER_VAR
}

and call the function.

static int dummy = init();

Upvotes: 3

Related Questions