What are undeclared identifier errors? What are common causes and how do I fix them?
Example error texts:
error C2065: 'cout' : undeclared identifier
'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:
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
To fix it, we must include the header:
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
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.
Another common source of beginner's error occur when you misspelled a variable:
int main() {
int aComplicatedName;
AComplicatedName = 1; /* mind the uppercase A */
return 0;
}
For example, this code would give an error, because you need to use std::string
:
#include <string>
int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}
void f() { g(); }
void g() { }
g
has not been declared before its first use. To fix it, either move the definition of g
before f
:
void g() { }
void f() { g(); }
Or add a declaration of g
before f
:
void g(); // declaration
void f() { g(); }
void g() { } // definition
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:
#include <iostream>
#include "stdafx.h"
The #include <iostream>
would be ignored. You need to move it below:
#include "stdafx.h"
#include <iostream>
Feel free to edit this answer.