#ifdef和未声明的标识符

#ifdef and undeclared identifier

本文关键字:标识符 未声明 #ifdef      更新时间:2023-10-16

我在Visual Studio 2017中开发了一个项目。以下代码:

#ifdef MY_DEFINE
#else
std::string txt = "abc";
#endif
output += txt;

没有编译-我得到一个错误:'txt': undeclared identifier

MY_DEFINE未定义,而else分支已编译。该代码是更大项目的一部分。我无法在默认的简单控制台应用程序中重现编译错误。这是否意味着该项目可能存在导致编译错误的某些设置?

您可以使用#error指令检查实际发生了什么:

#ifdef MY_DEFINE
#error It was defined
#else
#error It was NOT defined
std::string txt = "abc";
#endif
output += txt;

可能MY_DEFINE实际上是在您包含的其他头文件中定义的。通常,在Visual Studio中确定这一点的最简单方法就是将鼠标光标悬停在标识符上,然后查看它的内容,或者ctrl+单击以转到定义。但有时IDE中的这些提示与您编译的内容并不完全匹配。