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
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.
Misspelled variable
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;
}
Incorrect scope
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.
}
Use before declaration
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
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:
#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.
<iostream>
and trying to usestd::string
without having<string>
included. May be worth mentioning. – Decemvir