Ошибка use of undeclared identifier endl

Учусь работать в qt, загрузил пример с интернета
Вот код:

#include <QTextStream> // подключаем необходимый заголовочный файл


int main() {

    QTextStream out(stdout);

    // Создаем строку типа QString
    QString a = "love";

    // Добавляем текст в конец строки
    a.append(" chess");

    // Добавляем текст в начало строки
    a.prepend("I ");

    // Выводим строку
    out << a << endl;

    // Выводим количество символов строки
    out << "The a string has " << a.count() << " characters" << endl;

    // Выводим всю строку в верхнем регистре
    out << a.toUpper() << endl;

    // Выводим всю строку в нижнем регистре
    out << a.toLower() << endl;

    return 0;
}

На каждую строчку с endl выдает ошибку: use of undeclared identifier ‘endl’

задан 5 апр 2021 в 19:19

Женя Соловьев's user avatar

4

Если кто-то столкнется с данной проблемой то для них напишу здесь решение, потому что нигде я этой информации не нашел. Чтобы не было данной ошибки нужно писать вот так…

out << "Qt rocks!" << Qt::endl;

ответ дан 5 апр 2021 в 19:35

Женя Соловьев's user avatar

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.

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;
};

In this tutorial, we will learn how to fix a “use of undeclared identifier” compilation error in C++. The word identifier is used for the names we give to our variable.

This type of error deals with the cases where we make some mistakes while dealing with the identifiers i.e, this type of error is a compilation error that occurs when we make a mistake while working with the variables and their names. This type of error can occur due to multiple reasons and here we will discuss all those reasons.

How to Fix a “use of undeclared identifier” compilation error in C++

  1. VARIABLE NOT DECLARED: When we are using a variable sometimes we might forget to declare it. We keep on writing the code using the variable without declaring it. To fix this, we simply need to declare the variable before using it. For example:
    Here we are using the variable x without declaring it. This will give us an error. We simply need to declare x before using it to fix the error.
    #include<iostream>
    using namespace std;
    int main(){
        x=x+1;
        cout<<x;
        return 0;
    }
    //this code will give us the error
    //to fix this:
    #include<iostream>
    using namespace std;
    int main(){
        int x=0; //to whichever value we want to intialise
        x=x+1;
        cout<<x;
        return 0;
    }
  2. MISSPELLED VARIABLE NAME:  Sometimes while writing the code we may spell the variable name wrong. This is a common type of error because while typing it is very easy to make a spelling mistake. To fix this, simply check every instance of the variable you have used and make sure that it is spelled correctly. For example:
    Here we have spelled abx as abs and hence it gives us an error. To fix this, we make sure that all the variables are spelled correctly.
    #include<iostream> 
    using namespace std; 
    int main(){ 
        int abx=0;
        abx=abs+1; //spelled abx wrong
        cout<<abx; 
        return 0; 
    }
     //this code will give us the error 
    //to fix this:
    /#include<iostream> 
    using namespace std; 
    int main(){ 
        int abx=0;
        abx=abx+1; 
        cout<<abx; 
        return 0; 
    }
  3. OUT OF SCOPE VARIABLE:  If we try to use a variable out of its scope then also this error occurs as the variable remains undeclared out of its scope. To avoid this make sure that you are using a variable inside its scope only. For example:
    Here, the scope of i is only within the for loop. So, when we try to use i outside the loop it throws an error. To solve it simply declare i outside the loop so that the whole program inside the main function can use it.
    #include<iostream> 
    using namespace std; 
    int main(){ 
        int abx=0; 
        for(int i=0;i<5;i++){
            abx++;      //i is only declared for this scope
        }
        cout<<abx*i; //here i is not declared for the outer function
        return 0;  
    } 
    //this code will give us the error 
    //to fix this:
    
    #include<iostream> 
    using namespace std; 
    int main(){ 
        int abx=0,i=0; //i is declared for the main function
        for(i;i<5;i++){
            abx++;
         } 
        cout<<abx*i;//no error 
        return 0; 
    }
  4. LIBRARY NOT INCLUDED: If we try to use a data type such as vector without including its library we will get this error. To fix this, make sure that you are using an identifier only after including its library. For example, we are here using vector without including its library. This given an error. To solve it, simply include the required libraries beforehand.
    #include<iostream> 
    using namespace std; 
    int main(){ 
        vector<int> abx; //abx is not declared
        for(int i=0;i<5;i++){ 
            abx.push_back(i);
        } 
        cout<<abx[2];
        return 0; 
        } 
    //this code will give us the error 
    //to fix this:
    #include<iostream> 
    #include<vector>
    using namespace std; 
    int main(){ 
        vector<int> abx; //abx is declared 
        for(int i=0;i<5;i++){ 
            abx.push_back(i);
        } 
        cout<<abx[2];
        return 0; 
        }

READ MORE:

Errors in C++

Что такое необъявленные ошибки идентификатора? Каковы общие причины и как их исправить?

Пример текстов ошибок:

  • Для компилятора Visual Studio: error C2065: 'cout' : undeclared identifier
  • Для компилятора GCC: 'cout' undeclared (first use in this function)

39

Решение

Чаще всего они приходят из-за того, что забывают включить заголовочный файл, содержащий объявление функции, например, эта программа выдаст ошибку «необъявленный идентификатор»:

Отсутствует заголовок

int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}

Чтобы это исправить, мы должны включить заголовок:

#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}

Если вы написали заголовок и включили его правильно, заголовок может содержать неправильный включить охрану.

Чтобы узнать больше, смотрите http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.

Переменная с ошибкой

Другой распространенный источник ошибки новичка возникает, когда вы неправильно написали переменную:

int main() {
int aComplicatedName;
AComplicatedName = 1;  /* mind the uppercase A */
return 0;
}

Неправильный объем

Например, этот код выдаст ошибку, потому что вам нужно использовать std::string:

#include <string>

int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}

Использовать до объявления

void f() { g(); }
void g() { }

g не был объявлен до его первого использования. Чтобы это исправить, либо переместите определение g до f:

void g() { }
void f() { g(); }

Или добавить декларацию g до f:

void g(); // declaration
void f() { g(); }
void g() { } // definition

stdafx.h не сверху (специфично для VS)

Это зависит от Visual Studio. В VS нужно добавить #include "stdafx.h" перед любым кодом. Код до того, как он игнорируется компилятором, так что если у вас есть это:

#include <iostream>
#include "stdafx.h"

#include <iostream> будет проигнорировано Вам нужно переместить его ниже:

#include "stdafx.h"#include <iostream>

Не стесняйтесь редактировать этот ответ.

54

Другие решения

Рассмотрим похожую ситуацию в разговоре. Представьте, что ваш друг говорит вам: «Боб идет на ужин», а ты не представляешь, кто такой Боб. Вы будете в замешательстве, верно? Твой друг должен был сказать: «У меня есть коллега по работе по имени Боб. Боб подходит к обеду». Теперь Боб объявлен, и вы знаете, о ком говорит ваш друг.

Компилятор выдает ошибку «необъявленный идентификатор», когда вы пытаетесь использовать какой-то идентификатор (который будет именем функции, переменной, класса и т. Д.), И компилятор не видит объявления для него. То есть компилятор понятия не имеет, о чем вы говорите, потому что раньше его не видел.

Если вы получаете такую ​​ошибку в C или C ++, это означает, что вы не сказали компилятору о том, что вы пытаетесь использовать. Объявления часто встречаются в заголовочных файлах, поэтому, скорее всего, это означает, что вы не включили соответствующий заголовок. Конечно, может случиться так, что вы просто не помните, чтобы объявить сущность вообще.

Некоторые компиляторы выдают более конкретные ошибки в зависимости от контекста. Например, пытаясь скомпилировать X x; где тип X не был объявлен с Clang скажет вам «неизвестное имя типа X«. Это гораздо полезнее, потому что вы знаете, что он пытается интерпретировать X как тип. Тем не менее, если у вас есть int x = y;, где y еще не объявлено, он скажет вам «использование необъявленного идентификатора y«потому что есть некоторая двусмысленность в том, что именно y может представлять.

12

У меня была такая же проблема с пользовательским классом, который был определен в пространстве имен. Я пытался использовать класс без пространства имен, вызывая ошибку компилятора «идентификатор» MyClass «не определен».
Добавление

using namespace <MyNamespace>

или используя класс, как

MyNamespace::MyClass myClass;

решил проблему.

5

В C и C ++ все имена должны быть объявлены перед использованием. Если вы попытаетесь использовать имя переменной или функции, которая не была объявлена, вы получите ошибку «необъявленный идентификатор».

Однако функции — это особый случай в C (и только в C), в котором вам не нужно сначала объявлять их. Компилятор C будет предполагать, что функция существует с числом и типом аргументов, как в вызове. Если фактическое определение функции не совпадает, вы получите еще одну ошибку. Этот особый случай для функций не существует в C ++.

Вы исправляете ошибки такого рода, проверяя, что функции и переменные объявлены до их использования. В случае printf вам нужно включить заголовочный файл <stdio.h> (или же <cstdio> в C ++).

Для стандартных функций я рекомендую вам проверить, например, этот справочный сайт, и найдите функции, которые вы хотите использовать. Документация для каждой функции говорит вам, какой заголовочный файл вам нужен.

4

Эти сообщения об ошибках

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

означает, что вы используете имя printf но компилятор не видит, где было объявлено имя, и, соответственно, не знает, что это значит.

Любое имя, используемое в программе, должно быть объявлено до ее использования. Компилятор должен знать, что обозначает имя.

В этом конкретном случае компилятор не видит объявление имени printf , Как мы знаем (но не компилятор) это имя стандартной функции C, объявленной в заголовке <stdio.h> в C или в заголовке <cstdio> в C ++ и размещены в стандарте (std::) и глобальный (::) (не обязательно) пространства имен.

Поэтому, прежде чем использовать эту функцию, мы должны предоставить объявление ее имени компилятору путем включения соответствующих заголовков.

Например
C:

#include <stdio.h>

int main( void )
{
printf( "Hello Worldn" );
}

C ++:

#include <cstdio>

int main()
{
std::printf( "Hello Worldn" );
// or printf( "Hello Worldn" );
// or ::printf( "Hello Worldn" );
}

Иногда причиной такой ошибки является простая опечатка. Например, давайте предположим, что вы определили функцию PrintHello

void PrintHello()
{
std::printf( "Hello Worldn" );
}

но в основном вы сделали опечатку и вместо PrintHello ты напечатал printHello с строчной буквы «р».

#include <cstdio>

void PrintHello()
{
std::printf( "Hello Worldn" );
}

int main()
{
printHello();
}

В этом случае компилятор выдаст такую ​​ошибку, потому что он не видит объявление имени printHello, PrintHello а также printHello два разных имени, одно из которых было объявлено, а другое не объявлено, но используется в теле основного

3

Это похоже на использование функции без ее объявления. заголовочный файл будет содержать
функция printf (). Включите заголовочный файл в вашу программу, это решение для этого.
Некоторые пользовательские функции могут также вызывать ошибки, если они не были объявлены перед использованием. Если
это используется во всем мире без проб.

0

В большинстве случаев, если вы уверены, что импортировали данную библиотеку, Visual Studio поможет вам с IntelliSense.

Вот что сработало для меня:

Удостоверься что #include "stdafx.h" объявляется первым, то есть вверху всех ваших включений.

0

StarGame

0 / 0 / 0

Регистрация: 26.10.2015

Сообщений: 86

1

01.11.2015, 01:11. Показов 11794. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "iostream" 
#include "stdafx.h"
#include "cmath" 
#include "cstdio" 
using namespace std;
 
int main(void)
{
    int v;
    cout <<"Vvedite vozrast: "<<endl;
    cin >> v;
    if (1 <= v && v <= 10) cout << "Rebenok";
    else if (11 <= v && v <= 15) cout << "Podrostok";
    else if (16 <= v && v <= 20) cout << "Unosha";
    else if (21 <= v && v <= 30) cout << "Molodoi chelovek";
    else if (v>30) cout << "Vzroslii";
}

помогите cout,endl,cin undeclared identifier что делать ?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

01.11.2015, 01:11

Ответы с готовыми решениями:

error C2065: ‘endl’ : undeclared identifier
Здравствуйте всем!!!! У меня к вам следующий глупый вопрос: решил я попробовать на поприще…

Объекты cin, cout, endl и т.п
Вопрос. Можно ли использовать эти объекты по умолчанию или одной командой? Типа:
using std::&quot;все…

cin, cout, endl не определены
Всем здрасте=)

Есть исходник, он работает и всё с ним отлично, мне необходимо его…

Почему не определяются cout, cin, endl, system?
int i,n,k1,k2;
float min,s=0;
cout&lt;&lt;&quot; n=&quot;; cin&gt;&gt;n;
float* a=new float ;

3

16 / 16 / 12

Регистрация: 10.11.2012

Сообщений: 245

01.11.2015, 03:24

2

так то вроде всё нормально, но у меня компилятор жаловался на одну ненужную и непонятную строку
#include «stdafx.h»
попробуй убрать, у меня заработало как убрал её (Dev-C++)



0



zss

Модератор

Эксперт С++

13320 / 10454 / 6253

Регистрация: 18.12.2011

Сообщений: 27,910

01.11.2015, 06:34

3

Лучший ответ Сообщение было отмечено StarGame как решение

Решение

stdafx.h — Это приблуда MS Visual Studio — файл предкомпилированных заголовков.
Его подключение должно быть первой строкой кода.
Чтобы он не требовался, при создании проекта надо создавать пустой проект,
либо потом отключить эту опцию командой меню
Проект->Свойства->Свойства конфигурации->С/С++->Предварительно скомпилированные заголовки->
Не использовать

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream> 
using namespace std;
 
int main()
{
    unsigned int v;
    cout <<"Vvedite vozrast: "<<endl;
    cin >> v;
    if (v <= 10) 
        cout << "Rebenok";
    else if (11 <= v && v <= 15) 
        cout << "Podrostok";
    else if (16 <= v && v <= 20) 
        cout << "Unosha";
    else if (21 <= v && v <= 30) 
        cout << "Molodoi chelovek";
    else 
        cout << "Vzroslii";
    return 0;
}



1



hoggy

Эксперт С++

8731 / 4310 / 959

Регистрация: 15.11.2014

Сообщений: 9,754

01.11.2015, 10:31

4

Лучший ответ Сообщение было отмечено StarGame как решение

Решение

Цитата
Сообщение от StarGame
Посмотреть сообщение

помогите cout,endl,cin undeclared identifier что делать ?

заменить:

C++
1
2
3
4
#include "iostream" 
#include "stdafx.h"
#include "cmath" 
#include "cstdio"

на:

C++
1
2
3
4
#include "stdafx.h" //<--- должен быть первым
#include <iostream>
#include <cmath> 
#include <cstdio>

если ругнется на stdafx.h, выпиливайте его нафиг.



0



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;
};
  • Remove From My Forums
  • Question

  • I am new at C++ and I am having a little problem with Visual C++ 2005.

    I type in this source code

    #include <iostream>

    int main()

    {

    int x = 5;

    int y = 7;

    std::cout << endl;

    std::cout << x + y << » « << x * y;

    std::cout << end;

    return 0;

    }

    When I build my program I get two errors and those are

    error C2065: ‘endl’ : undeclared identifier

    error C2065: ‘end’ : undeclared identifier

    What is the problem and how can I fix it?


Answers

  • try adding: std:: before both of your endl’s (Oh and, check your typo on the 2nd endl =P)

    #include <iostream>

    int main()
    {

    int x = 5;

    int y = 7;

    std::cout << std::endl;

    std::cout << x + y << » » << x * y;

    std::cout << std::endl;

    return 0;

    }

  • Or do the following:

    #include <iostream>
    using namespace std;

    This will alleviate having to use std:: in all places.

  • Ошибка usc на lexus 570
  • Ошибка usb001 не печатает принтер
  • Ошибка usb флешки диск защищен от записи
  • Ошибка usb накопителя на планшете
  • Ошибка usb накопителя задание отменено 01 куосера