What is an #39;undeclared identifier#39; error and how do I fix it?(什么是“未声明的标识符错误,我该如何解决?)
问题描述
什么是未声明的标识符错误?什么是常见原因,我该如何解决?
错误文本示例:
- 对于 Visual Studio 编译器:
error C2065: 'cout' : undeclared identifier
- 对于 GCC 编译器:
'cout' 未声明(首次在此函数中使用)
最常见的原因是忘记包含包含函数声明的头文件,例如,这个程序会给出'undeclared identifier'错误:
>
缺少标题
要修复它,我们必须包含标题:
如果您编写了标题并正确包含了它,则标题可能包含错误的include guard.
要了解更多信息,请参阅 http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.
拼写错误的变量
初学者错误的另一个常见原因是变量拼写错误:
范围不正确
比如这段代码会报错,因为你需要使用std::string
:
声明前使用
g
在第一次使用之前没有被声明.要修复它,请在 f
之前移动 g
的定义:
或者在f
之前添加一个g
的声明:
stdafx.h 不在顶部(VS 特定)
这是特定于 Visual Studio 的.在VS中,您需要在任何代码之前添加#include "stdafx.h"
.编译器忽略之前的代码,所以如果你有这个:
#include
将被忽略.你需要把它移到下面:
随意编辑这个答案.
What are undeclared identifier errors? What are common causes and how do I fix them?
Example error texts:
- For the Visual Studio compiler:
error C2065: 'cout' : undeclared identifier
- For the GCC compiler:
'cout' undeclared (first use in this function)
They most often come from forgetting to include the header file that contains the function declaration, for example, this program will give an 'undeclared identifier' error:
Missing header
To fix it, we must include the header:
If you wrote the header and included it correctly, the header may contain the wrong include guard.
To read more, see http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.
Misspelled variable
Another common source of beginner's error occur when you misspelled a variable:
Incorrect scope
For example, this code would give an error, because you need to use std::string
:
Use before declaration
g
has not been declared before its first use. To fix it, either move the definition of g
before f
:
Or add a declaration of g
before f
:
stdafx.h not on top (VS-specific)
This is Visual Studio-specific. In VS, you need to add #include "stdafx.h"
before any code. Code before it is ignored by the compiler, so if you have this:
The #include <iostream>
would be ignored. You need to move it below:
Feel free to edit this answer.
这篇关于什么是“未声明的标识符"错误,我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!