Ошибка компилятора c2065

I ran across this error after just having installed vs 2010 and just trying to get a nearly identical program to work.

I’ve done vanilla C coding on unix-style boxes before, decided I’d play with this a bit myself.

The first program I tried was:

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World!";
    return 0;
}

The big thing to notice here… if you’ve EVER done any C coding,

int _tmain(int argc, _TCHAR* argv[])

Looks weird. it should be:

int main( int argc, char ** argv )

In my case I just changed the program to:

#include <iostream>
using namespace std;

int main()
{
     cout << "Hello world from  VS 2010!n";
     return 0;
}

And it worked fine.

Note: Use CTRL + F5 so that the console window sticks around so you can see the results.

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.

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. Показов 3018. Ответов 16

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


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

Добрый день.
При компиляции через visual studio 2019 вот такая ошибка.

1>C:UsersserversourcereposFirtsCPPSource3.cpp(6,2): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(8,10): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(11,2): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(11,12): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(12,23): error C2065: carrots: необъявленный идентификатор

При компиляции через Borland всё ок. Сверил свой код с книжкой, вроде всё ок. Подскажите в чём проблема.

Компилируемый код

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
int main()
{
    using namespace std;
    int carrots;
    cout << "How many carrots do you have?" << endl;
    cin >> carrots;
    cout << "Here are two more. ";
    carrots = carrots + 2;
    cout << "How you have " << carrots << " carrots" << endl;
    cin.get();
    cin.get();
    return 0;
}



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

C++
1
2
3
4
5
6
#include <iostream>
using namespace std;
 
int main()
{
    int carrots;

И проверь, на всякий случай, что у тебя все буквы в carrots латинские



0



Майкл Скоуфилд

11 / 10 / 3

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

Сообщений: 238

06.09.2019, 12:51

 [ТС]

3

Результат тот же. Такое ощущение, что стандартный компилятор от VS работает через *опу.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
 
int main()
{
    int carrots;
    cout << "How many carrots do you have?" << endl;
    cin >> carrots;
    cout << "Here are two more. ";
    carrots = carrots + 2;
    cout << "How you have " << carrots << " carrots" << endl;
    cin.get();
    cin.get();
    return 0;
}

Может у кого-то ещё будут какие-то идеи как прекратить такие ругательства?

1>C:UsersserversourcereposFirtsCPPSource3.cpp(6,2): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(8,10): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(11,2): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(11,12): error C2065: carrots: необъявленный идентификатор
1>C:UsersserversourcereposFirtsCPPSource3.cpp(12,23): 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

Я конечно извиняюсь но можно как для криворукого ткнуть носом где эти параметры.
Гугл мне не подсказал где конкретно их найти, а изобилие настроек в VS не может не радовать.
http://skrinshoter.ru/s/060919/067JX6tN



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

Перешёл во вкладку «проект»-«Свойства»
Link



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

Вот так заходил в менюшку
Link



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

Спасибо что объяснили.
Нашёл нужные параметры, они по умолчанию настроены так как вы и рекомендовали.
Link



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

Вы не поняли.
Ругалась она когда только первый раз создал файл и попробовал скомпилировать.
Убрал через HEX, пошло.
Потом добавил переменную carrots и вылезли новые косяки, описанные выше.
Лишних кракозябр нет в коде, чего оно орало «Не объявлен идентификатор я хз.



0



  • Remove From My Forums
  • Question

  • Im having trouble building a programme when i do it fails and says this:

    error C2065: ‘cout’ : undeclared identifier

    I built a programme before using «cout» which works fine called test here it is

    /*
    this is a test
    */
     #include «StdAfx.h»

    #include <iostream>
    using namespace std;

    int main()
    {
     cout << «hi this is a test «

     
     ;system («pause»);

      ;return 0;
    }

    that one works well it is a CLR console application.

    i am using microsoft visual basic 2010

    the programme that doesnt work and gets the error

    error C2065: ‘cout’ : undeclared identifier

    i think is a win32 application

    i am new to C++ and have just started learning,can anyone help?

Answers

  • Hi,

    In Visual Studio there are two kinds of *.exe binaries, windows applications and console applications. A console application is has a single console window where all input, output and errors are displayed. While a windows application usually presents a window
    and interacts with the user using the Microsoft GUI.

    For developers, the main difference between Windows Applications and Console Applications is that the former’s entry point is WinMain() or wWinMain(), while the latter’s entry point is main() or wmain().

    We can use cout in console applications to output strings to the console window. While in Windows applications, cout cannot be used and we can use other APIs such as TextOut instead to output on the window.

    So please separate console applications from windows applications. It is not proper for us to mix the two types of applications together.

    I hope this reply is helpful to you.
    Best regards,


    Helen Zhao [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by

      Monday, November 28, 2011 9:03 PM

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора c2064
  • Ошибка компилятора c2061
  • Ошибка компилятора c2040
  • Ошибка компилятора 1af8
  • Ошибка компетенции это