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.
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2065 |
Compiler Error C2065 |
06/29/2022 |
C2065 |
C2065 |
78093376-acb7-45f5-9323-5ed7e0aab1dc |
Compiler Error C2065
‘identifier‘ : undeclared identifier
The compiler can’t find the declaration for an identifier. There are many possible causes for this error. The most common causes of C2065 are that the identifier hasn’t been declared, the identifier is misspelled, the header where the identifier is declared isn’t included in the file, or the identifier is missing a scope qualifier, for example, cout
instead of std::cout
. For more information on declarations in C++, see Declarations and Definitions (C++).
Here are some common issues and solutions in greater detail.
The identifier is undeclared
If the identifier is a variable or a function name, you must declare it before it can be used. A function declaration must also include the types of its parameters before the function can be used. If the variable is declared using auto
, the compiler must be able to infer the type from its initializer.
If the identifier is a member of a class or struct, or declared in a namespace, it must be qualified by the class or struct name, or the namespace name, when used outside the struct, class, or namespace scope. Alternatively, the namespace must be brought into scope by a using
directive such as using namespace std;
, or the member name must be brought into scope by a using
declaration, such as using std::string;
. Otherwise, the unqualified name is considered to be an undeclared identifier in the current scope.
If the identifier is the tag for a user-defined type, for example, a class
or struct
, the type of the tag must be declared before it can be used. For example, the declaration struct SomeStruct { /*...*/ };
must exist before you can declare a variable SomeStruct myStruct;
in your code.
If the identifier is a type alias, the type must be declared by a using
declaration or typedef
before it can be used. For example, you must declare using my_flags = std::ios_base::fmtflags;
before you can use my_flags
as a type alias for std::ios_base::fmtflags
.
Example: misspelled identifier
This error commonly occurs when the identifier name is misspelled, or the identifier uses the wrong uppercase and lowercase letters. The name in the declaration must exactly match the name you use.
// C2065_spell.cpp // compile with: cl /EHsc C2065_spell.cpp #include <iostream> using namespace std; int main() { int someIdentifier = 42; cout << "Some Identifier: " << SomeIdentifier << endl; // C2065: 'SomeIdentifier': undeclared identifier // To fix, correct the spelling: // cout << "Some Identifier: " << someIdentifier << endl; }
Example: use an unscoped identifier
This error can occur if your identifier isn’t properly scoped. If you see C2065 when you use cout
, a scope issue is the cause. When C++ Standard Library functions and operators aren’t fully qualified by namespace, or you haven’t brought the std
namespace into the current scope by using a using
directive, the compiler can’t find them. To fix this issue, you must either fully qualify the identifier names, or specify the namespace with the using
directive.
This example fails to compile because cout
and endl
are defined in the std
namespace:
// C2065_scope.cpp // compile with: cl /EHsc C2065_scope.cpp #include <iostream> // using namespace std; // Uncomment this line to fix int main() { cout << "Hello" << endl; // C2065 'cout': undeclared identifier // C2065 'endl': undeclared identifier // Or try the following line instead std::cout << "Hello" << std::endl; }
Identifiers that are declared inside of class
, struct
, or enum class
types must also be qualified by the name of their enclosing scope when you use them outside of that scope.
Example: precompiled header isn’t first
This error can occur if you put any preprocessor directives, such as #include
, #define
, or #pragma
, before the #include
of a precompiled header file. If your source file uses a precompiled header file (that is, if it’s compiled by using the /Yu
compiler option) then all preprocessor directives before the precompiled header file are ignored.
This example fails to compile because cout
and endl
are defined in the <iostream>
header, which is ignored because it’s included before the precompiled header file. To build this example, create all three files, then compile pch.h
(some versions of Visual Studio use stdafx.cpp
), then compile C2065_pch.cpp
.
// pch.h (stdafx.h in Visual Studio 2017 and earlier) #include <stdio.h>
The pch.h
or stdafx.h
source file:
// pch.cpp (stdafx.cpp in Visual Studio 2017 and earlier) // Compile by using: cl /EHsc /W4 /c /Ycstdafx.h stdafx.cpp #include "pch.h"
Source file C2065_pch.cpp
:
// C2065_pch.cpp // compile with: cl /EHsc /W4 /Yustdafx.h C2065_pch.cpp #include <iostream> #include "stdafx.h" using namespace std; int main() { cout << "Hello" << endl; // C2065 'cout': undeclared identifier // C2065 'endl': undeclared identifier }
To fix this issue, add the #include of <iostream>
into the precompiled header file, or move it after the precompiled header file is included in your source file.
Example: missing header file
The error can occur if you haven’t included the header file that declares the identifier. Make sure the file that contains the declaration for the identifier is included in every source file that uses it.
// C2065_header.cpp // compile with: cl /EHsc C2065_header.cpp //#include <stdio.h> int main() { fpos_t file_position = 42; // C2065: 'fpos_t': undeclared identifier // To fix, uncomment the #include <stdio.h> line // to include the header where fpos_t is defined }
Another possible cause is if you use an initializer list without including the <initializer_list> header.
// C2065_initializer.cpp // compile with: cl /EHsc C2065_initializer.cpp // #include <initializer_list> int main() { for (auto strList : {"hello", "world"}) if (strList == "hello") // C2065: 'strList': undeclared identifier return 1; // To fix, uncomment the #include <initializer_list> line }
You may see this error in Windows Desktop app source files if you define VC_EXTRALEAN
, WIN32_LEAN_AND_MEAN
, or WIN32_EXTRA_LEAN
. These preprocessor macros exclude some header files from windows.h
and afxv_w32.h
to speed compiles. Look in windows.h
and afxv_w32.h
for an up-to-date description of what’s excluded.
Example: missing closing quote
This error can occur if you’re missing a closing quote after a string constant. It’s an easy way to confuse the compiler. The missing closing quote may be several lines before the reported error location.
// C2065_quote.cpp // compile with: cl /EHsc C2065_quote.cpp #include <iostream> int main() { // Fix this issue by adding the closing quote to "Aaaa" char * first = "Aaaa, * last = "Zeee"; std::cout << "Name: " << first << " " << last << std::endl; // C2065: 'last': undeclared identifier }
Example: use iterator outside for loop scope
This error can occur if you declare an iterator variable in a for
loop, and then you try to use that iterator variable outside the scope of the for
loop. The compiler enables the /Zc:forScope
compiler option by default. For more information, see Debug iterator support.
// C2065_iter.cpp // compile with: cl /EHsc C2065_iter.cpp #include <iostream> #include <string> int main() { // char last = '!'; std::string letters{ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; for (const char& c : letters) { if ('Q' == c) { std::cout << "Found Q!" << std::endl; } // last = c; } std::cout << "Last letter was " << c << std::endl; // C2065 // Fix by using a variable declared in an outer scope. // Uncomment the lines that declare and use 'last' for an example. // std::cout << "Last letter was " << last << std::endl; // C2065 }
Example: preprocessor removed declaration
This error can occur if you refer to a function or variable that is in conditionally compiled code that isn’t compiled for your current configuration. The error can also occur if you call a function in a header file that currently isn’t supported in your build environment. If certain variables or functions are only available when a particular preprocessor macro is defined, make sure the code that calls those functions can only be compiled when the same preprocessor macro is defined. This issue is easy to spot in the IDE: The declaration for the function is greyed out if the required preprocessor macros aren’t defined for the current build configuration.
Here’s an example of code that works when you build in Debug, but not Release:
// C2065_defined.cpp // Compile with: cl /EHsc /W4 /MT C2065_defined.cpp #include <iostream> #include <crtdbg.h> #ifdef _DEBUG _CrtMemState oldstate; #endif int main() { _CrtMemDumpStatistics(&oldstate); std::cout << "Total count " << oldstate.lTotalCount; // C2065 // Fix by guarding references the same way as the declaration: // #ifdef _DEBUG // std::cout << "Total count " << oldstate.lTotalCount; // #endif }
Example: C++/CLI type deduction failure
This error can occur when calling a generic function, if the intended type argument can’t be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).
// C2065_b.cpp // compile with: cl /clr C2065_b.cpp generic <typename ItemType> void G(int i) {} int main() { // global generic function call G<T>(10); // C2065 G<int>(10); // OK - fix with a specific type argument }
Example: C++/CLI attribute parameters
This error can also be generated as a result of compiler conformance work that was done for Visual Studio 2005: parameter checking for Visual C++ attributes.
// C2065_attributes.cpp // compile with: cl /c /clr C2065_attributes.cpp [module(DLL, name=MyLibrary)]; // C2065 // try the following line instead // [module(dll, name="MyLibrary")]; [export] struct MyStruct { int i; };
Столкнулся с проблемой, но на существующих топиках об этой проблеме не нашел решения. Я в затруднении, все include’ы правильно расставлены вроде, да и средствами visual studio у меня получается перейти к объявлению функции, а ошибка все равно вылетает: «С2065. resizeCallback: необъявленный идентификатор». Вот код:
#pragma once
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define internal static
#define local_persist static
#define global_variable static
namespace core {
namespace graphics {
class Window
{
private:
const char* name;
int width, height;
GLFWwindow* window;
public:
Window(const char* name, int width, int heignt);
~Window();
bool closed();
void MainLoop();
private:
bool init();
void clear();
void update();
void render();
friend void resizeCallback(GLFWwindow* window, int width, int height);
};
}}
Вот второй файл
#include "window.h"
namespace core {
namespace graphics {
Window::Window(const char* name, int width, int height)
{
this->name = name;
this->width = width;
this->height = height;
if (!init())
{
glfwTerminate();
}
}
Window::~Window()
{
glfwTerminate();
}
bool Window::init()
{
if (!glfwInit())
{
std::cout << "LooL. GLFW isn't ok" << std::endl;
glfwTerminate();
return false;
}
window = glfwCreateWindow(width, height, name, NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetWindowSizeCallback(window, resizeCallback);
if (glewInit() != GLEW_OK)
{
std::cout << "glew isn't okay" << std::endl;
return false;
}
return true;
}
void Window::update()
{
glfwPollEvents();
glfwSwapBuffers(window);
}
void Window::clear()
{
glClear(GL_COLOR_BUFFER_BIT);
}
void Window::render()
{
glBegin(GL_QUADS);
glVertex2f(0.5f, 0.5f);
glVertex2f(0.5f, -0.5f);
glVertex2f(-0.5f, -0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
}
void Window::MainLoop()
{
update();
clear();
render();
}
bool Window::closed()
{
return (glfwWindowShouldClose(window)) == 1;
}
void resizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
}}
In this tutorial, we will learn about the compiler error C2065 in C++. We look at possible reasons for this error and their corresponding solutions.
The error message displayed for C2065 is:
‘identifier‘: undeclared identifier
This means that there is some issue with the code and that the compiler is unable to compile the code until this is fixed.
Compiler Error C2065 in C++
Identifiers are the names we give variables or functions in our C++ program. We get the error C2065 when we use such identifiers without first declaring them. Sometimes we may think that we have declared these identifiers, but there is a chance that we have not done so properly. I have shown a simple example below where we get the C2065 error message while compiling the code.
int main() { // uncommenting the following line removes the error // int i; i = 5; return 0; }
This is because we are using the variable ‘i’ without first declaring it.
The following sections have some common reasons and solutions for the C2065 error message.
Identifier is misspelt
This is a very common mistake that we all make. Sometimes we type the identifier wrong which results in the C2065 error message. Here are a few examples.
int main() { int DOB; int students[50]; dob = 32; // we declared 'DOB' but used 'dob' student[0] = 437; // we declared 'students' but used 'student' return 0; }
Identifier is unscoped
We must only use identifiers that are properly scoped. In the example given below, we declare ‘a’ inside the ‘if‘ statement. As a result, its scope is restricted to that ‘if‘ block.
int main() { int n = 5; if (n > 3) { int a = 3; a++; } // a cannot be used outside its scope a = 5; return 0; }
We must also bring library functions and operators into the current scope. A very common example of this is the ‘cout‘ statement which is defined in the ‘std‘ namespace. The following code results in the C2065 error.
#include <iostream> int main() { cout << "Hello World"; return 0; }
This error can be removed by either of the following methods.
#include <iostream> int main() { // we fully qualify the identifier using the // reuired namespace std::cout << "Hello World"; return 0; }
or
#include <iostream> // we bring the std namespace into the scope using namespace std; int main() { cout << "Hello World"; return 0; }
Precompiled header is not first
Let us say we have a precompiled header file. All other preprocessor directives must be put after the #include statement of the precompiled header. Thus, the following code having the precompiled header “pch.h” results in a C2065 error.
#include <iostream> #include "pch.h" using namespace std; int main() { cout << "Hello World"; return 0; }
We can fix this by moving the including of pch.h to the top as shown below.
#include "pch.h" #include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; }
The necessary header file is not included
We need to include header files if we are to use certain identifiers. We see the C2065 error message in the following code as we need to include the string header to use objects of string type.
// Uncomment the following line for the code to work // #include <string> using namespace std; int main() { string s; return 0; }
The closing quote is missing
We need to properly close quotes for the code to work correctly. In the example given below, the C2065 error shows up because the compiler does not properly recognise ‘d’.
int main() { // we need a closing quote (") after 'dog' in the following line char c[] = "dog, d[] = "cat"; d[0] = 'b'; return 0; }
Conclusion
In this tutorial, we looked at some possible reasons for the compiler error C2065 in C++. We also learnt about possible solutions. We may obtain this message for other reasons. Here is the link to Microsoft’s documentation for the C2065 error in Visual Studio 2019.
Майкл Скоуфилд 11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
||||
1 |
||||
05.09.2019, 20:07. Показов 3050. Ответов 16 Метки c2065 (Все метки)
Добрый день. 1>C:UsersserversourcereposFirtsCPPSource3.cpp(6,2): error C2065: carrots: необъявленный идентификатор При компиляции через Borland всё ок. Сверил свой код с книжкой, вроде всё ок. Подскажите в чём проблема. Компилируемый код
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
05.09.2019, 20:07 |
16 |
oleg-m1973 6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
||||
06.09.2019, 08:52 |
2 |
|||
При компиляции через visual studio 2019 вот такая ошибка. Попробуй вынести using namespace std; за фукнцию main
И проверь, на всякий случай, что у тебя все буквы в carrots латинские
0 |
Майкл Скоуфилд 11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
||||
06.09.2019, 12:51 [ТС] |
3 |
|||
Результат тот же. Такое ощущение, что стандартный компилятор от VS работает через *опу.
Может у кого-то ещё будут какие-то идеи как прекратить такие ругательства? 1>C:UsersserversourcereposFirtsCPPSource3.cpp(6,2): error C2065: carrots: необъявленный идентификатор
0 |
6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
06.09.2019, 12:55 |
4 |
Может у кого-то ещё будут какие-то идеи как прекратить такие ругательства? Проверь в настройках проекта с/c++ -> General -> Warnings Level — поставь Level3 и Treat Warnings As Errors, поставь No
0 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
06.09.2019, 13:11 [ТС] |
5 |
Я конечно извиняюсь но можно как для криворукого ткнуть носом где эти параметры.
0 |
6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
06.09.2019, 13:13 |
6 |
Я конечно извиняюсь но можно как для криворукого ткнуть носом где эти параметры. Меню Project, самая нижняя — Properties
0 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
06.09.2019, 13:19 [ТС] |
7 |
Перешёл во вкладку «проект»-«Свойства»
0 |
6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
06.09.2019, 13:29 |
8 |
Перешёл во вкладку «проект»-«Свойства» Это свойства файла, а не проекта Главное меню «Проект», которое сверху
0 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
06.09.2019, 13:53 [ТС] |
9 |
Вот так заходил в менюшку
0 |
6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
06.09.2019, 14:00 |
10 |
Вот так заходил в менюшку У тебя там справа «Обозреватель решений» нажми правой кнопкой на FirtsCPP (он как раз выделен) и выбери свойства
1 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
06.09.2019, 14:07 [ТС] |
11 |
Спасибо что объяснили.
0 |
6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
06.09.2019, 14:10 |
12 |
Спасибо что объяснили. Это не ошибки сборки, можно на них забить. Там в окне с ошибками сверху есть «Сборка и Intelisense», выбери там просто «Сборка»
0 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
06.09.2019, 14:18 [ТС] |
13 |
Правильно вас понял? Link Если да то собрать решение оно не даёт, ругается на эти ошибки и exe файл не компилится.
0 |
6577 / 4562 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
06.09.2019, 15:24 |
14 |
Решение
Если да то собрать решение оно не даёт, ругается на эти ошибки и exe файл не компилится. Не должго быть этих ошибок.
1 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
06.09.2019, 15:38 [ТС] |
15 |
Вот теперь завелось. P.S. При создание этого проекта (неработающей версии) изначально были бока. Иероглифы в коде, которых я точно не ставил и ничего не откуда не копировал. Увидеть их смог только через HEX редактор.
0 |
174 / 66 / 21 Регистрация: 06.07.2017 Сообщений: 353 |
|
08.09.2019, 00:07 |
16 |
Увидеть их смог только через HEX редактор Вот поэтому студия и ругалась на идентификаторы которых Вы визуально не видели. Но такое, как правило, бывает при использовании CopyPaste. Добавлено через 6 минут
0 |
11 / 10 / 3 Регистрация: 25.09.2015 Сообщений: 238 |
|
08.09.2019, 10:02 [ТС] |
17 |
Вы не поняли.
0 |