has has - 1 month ago 5
C++ Question

static variable in #define directive c++

Is it possible to declare static variable in a

#define
directive?

// header file
#define TEXT_ENUM
#ifdef TEXT_ENUM
#define TEXT_HANDLING_MACRO \
static const char * TEXT[]; \
static const char * getText( int _enum ) { \
return TEXT[_enum]; \
}
#else
#define TEXT_HANDLING_MACRO
#endif

struct Foo {
TEXT_HANDLING_MACRO
};

// cpp file
#include "foo.h"

const char * Foo::TEXT[] = {
"ONE",
"TWO",
"THREE",
0
};


How compiler will resolve static const char *, when I include this header file in some other file and try to access
Foo::TEXT[]
.

Answer

Is it possible to declare static variable in a #define directive?

Yes, it is possible.

How compiler will resolve static const char *, when I include this header file in some other file and try to access Foo::TEXT[].

It's resolved at the linking stage.