我正在使用预处理器 #define 宏来计算头文件中函数的数量:
#define __INDEX -1
//First group of functions
void func1(void);
#define __FUNC1_INDEX __INDEX + 1
void func2(void);
#define __FUNC2_INDEX __FUNC1_INDEX + 1
#undef __INDEX
#define __INDEX __FUNC2_INDEX
//Second group of functions
void func3(void);
#define __FUNC3_INDEX __INDEX + 1
void func4(void);
#define __FUNC4_INDEX __FUNC3_INDEX + 1
#undef __INDEX
#define __INDEX __FUNC4_INDEX
//Third group of functions
void func5(void);
#define __FUNC5_INDEX __INDEX + 1
void func6(void);
#define __FUNC6_INDEX __FUNC5_INDEX + 1
#undef __INDEX
#define __INDEX __FUNC6_INDEX
#define __NUM_FUNCTIONS __INDEX + 1
预处理器很好地完成了前两组函数,但是当它到达该行时:
#define __FUNC5_INDEX __INDEX + 1
我收到 __INDEX 的“未在此范围内定义”错误。真正令人困惑的是,在第二组函数中[成功]完成了完全相同的事情; __FUNC3_INDEX 的值为 __INDEX + 1。据我所知,任何地方都没有错别字……有什么问题?
我正在使用 g++ 4.8。
最佳答案
你不能用预处理器宏来计算。它们只是字符串扩展。
预处理器完成后:
#define __FUNC5_INDEX __INDEX + 1
#define __FUNC6_INDEX __FUNC5_INDEX + 1
#undef __INDEX
#define __INDEX __FUNC6_INDEX
以下定义有效:
__FUNC5_INDEX → __INDEX + 1
__FUNC6_INDEX → __FUNC5_INDEX + 1
__INDEX → __FUNC6_INDEX
没有进行任何计算。此外,没有替换在 #define
指令中执行。
现在,当您尝试展开 __INDEX
(可能作为 __NUM_FUNCTIONS
展开的一部分时,将发生以下情况:
__INDEX → __FUNC6_INDEX
→ __FUNC5_INDEX + 1
→ __INDEX + 1 + 1
此时,宏扩展停止,因为您无法在其自身扩展内扩展宏。 token 保持原样。
因此,您最终将在程序中使用符号 __INDEX
作为变量。但是由于变量 __INDEX
从未被定义,你会得到一个错误。
顺便说一句,不要使用以两个下划线或一个下划线和一个大写字母开头的符号。这些是为标准库保留的。
关于c++ - 宏未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556568/