Reputation: 43
I encountered a problem when declare some global variables using macros. Here is the case:
the original code:
/* some_config.h */
static const std::string KEYWORDS_A[] = {"AXX", "AYY"};
static const std::vector<std::string> KEYWORDS_A_VEC(KEYWORDS_A, KEYWORDS_A + sizeof(KEYWORDS_A) / sizeof(KEYWORDS_A[0]));
static const std::string KEYWORDS_B[] = {"BXX", "BYY"};
static const std::vector<std::string> KEYWORDS_B_VEC(KEYWORDS_B, KEYWORDS_B + sizeof(KEYWORDS_B) / sizeof(KEYWORDS_B[0]));
the current code:
/* some_config.h */
#define REGISTER_VEC(NAME) \
static const std::vector<std::string> KEYWORDS_##NAME_VEC(KEYWORDS_##NAME, KEYWORDS_##NAME + sizeof(KEYWORDS_##NAME) / sizeof(KEYWORDS_##NAME[0]))
static const std::string KEYWORDS_A[] = {"AXX", "AYY"};
REGISTER_VEC(A);
static const std::string KEYWORDS_B[] = {"BXX", "BYY"};
REGISTER_VEC(B);
the some_config.h was included in some.cpp in which the variables KEYWORDS_A_VEC and KEYWORDS_B_VEC were used. However, for the current code, the g++ compiler will give an error of not finding the definition of KEYWORDS_A_VEC and KEYWORDS_A_VEC.
Is there anything wrong with the code? thanks for your help.
Upvotes: 2
Views: 1261
Reputation: 272567
Your compilation problem is caused because you need a tokenization thing in every place that you intend to tokenize, e.g.:
#define REGISTER_NAME(NAME) blah_##NAME##_blah
(Note use of ##
on both sides of NAME
.)
As to whether this is good practice, I would say no. You have a single macro instantiating multiple variables, which is confusing to the reader of your code. Many IDEs and debuggers will get confused by this sort of thing, which means that a reader will have to do a lot of manual hunting to work out where variables are magically being declared.
Upvotes: 3