Ошибка с2065 visual studio
I am working on the 'driver' part of my programing assignment and i keep getting this absurd error:
error C2065: 'cout' : undeclared identifier
I have even tried using the std::cout but i get another error that says: IntelliSense: namespace "std" has no member "cout" when i have declared using namespace std, included iostream + i even tried to use ostream
I know it's a standard noob question but this has stumped me and I'm a novice (meaning: I've programed before. )
I'm using Visual Studio 2010 and running Windows 7. All of the .h files have "using namespace std" and include iostream and ostream.
"NOTE: all of the .h files include namespace std - and include io and o streams. "
26 Answers 26
These will not work.
Yeah, this on should be the accepted answer. Most of the others work as well, but this states it very clearly. @Wallter
write this code, it works perfectly..
I had same problem on Visual Studio C++ 2010. It's easy to fix. Above the main() function just replace the standard include lines with this below but with the pound symbol in front of the includes.
The include "stdafx.h" is ok
But you can't use cout unless you have included using namespace std
If you have not included namespace std you have to write std::cout instead of simple cout
This is the correct answer. You need to use `using namespace std' where cout resides. In modern C++, all functions are within is own namespace.
I have seen that if you use
then you will get the problem.
(notice - without the .h)
then you will not get the problem you mentioned.
@JavaRunner: Because the file is named iostream . It is not named iostream.h . iostream.h does not exist. Simple as that.
The code below compiles and runs properly for me using gcc. Try copy/pasting this and see if it works.
yeah same thing - Error 1 error C2065: 'cout' : undeclared identifier && IntelliSense: identifier "cout" is undefined
Does std::cout work? I don't know much about Visual Studio, are you sure you've set the project up correctly as a C++ project? If you open the file iostream does it contain a cout declaration?
Given that VS2010 is still beta it might be a bug (which beta version are you using?). But I find it hard to believe that something so basic doesn't work correctly.
If the only file you include is iostream and it still says undefined, then maybe iostream doesn't contain what it's supposed to. Is it possible that you have an empty file coincidentally named "iostream" in your project?
I've seen similar things happen when I was using the .c file extension with C++ code. Other than that, I'd have to agree with everyone about a buggy installation. Does it work if you try to compile the project with an earlier release of VS? Try VC++ Express 2008. Its free on msdn.
Such a silly solution in my case:
The above was odered as per example a, when I changed it to resemble example b below.
My code compiled like a charm. Try it, guaranteed to work.
I have VS2010, Beta 1 and Beta 2 (one on my work machine and one at home), and I've used std plenty without issues. Try typing:
And see if Intellisense gives you anything. If it gives you the usual stuff ( abort , abs , acos , etc.), except for cout , well then, that is quite a puzzler. Definitely look into your C++ headers in that case.
Beyond that, I would just add to make sure you're running a regular, empty project (not CLR, where Intellisense is crippled), and that you've actually attempted to build the project at least once. As I mentioned in a comment, VS2010 parses files once you've added an include ; it could be that something stuck the parser and it didn't "find" cout right away. (In which case, try restarting VS maybe?)
Компилятору не удается найти объявление идентификатора. Эта ошибка имеет несколько возможных причин. Наиболее распространенными причинами C2065 является то, что идентификатор не был объявлен, идентификатор написан неправильно, заголовок, где объявляется идентификатор, не включается в файл, или в идентификаторе отсутствует квалификатор области, например, cout вместо std::cout . Дополнительные сведения об объявлениях в C++ см. в разделе объявления и определения (c++).
Ниже приведены некоторые распространенные проблемы и более подробные решения.
Идентификатор не объявлен
Если идентификатор является переменной или именем функции, его необходимо объявить перед тем, как его можно будет использовать. Перед использованием функции в объявлении функции также должны быть включены типы его параметров. Если переменная объявлена с помощью auto , компилятор должен иметь возможность определить тип из его инициализатора.
Если идентификатор является членом класса или структуры или объявлен в пространстве имен, он должен уточняться именем класса или структуры или именем пространства имен при использовании вне структуры, класса или области пространства имен. Кроме того, пространство имен должно быть помещено в область с помощью using директивы, такой как using namespace std; , или имя члена должно быть помещено в область с помощью using объявления, такого как using std::string; . В противном случае неполное имя считается необъявленным идентификатором в текущей области.
Если идентификатор является тегом для определяемого пользователем типа, например, class или struct , тип тега должен быть объявлен до его использования. Например, объявление struct SomeStruct < /*. */ >; должно существовать, прежде чем можно будет объявить переменную SomeStruct myStruct; в коде.
Если идентификатор является псевдонимом типа, тип должен быть объявлен с помощью using объявления или typedef перед тем, как его можно будет использовать. Например, необходимо объявить using my_flags = std::ios_base::fmtflags; , прежде чем можно будет использовать my_flags в качестве псевдонима типа для std::ios_base::fmtflags .
Пример: идентификатор с ошибками
Эта ошибка обычно возникает, когда имя идентификатора написано неправильно или идентификатор использует неправильные прописные и строчные буквы. Имя в объявлении должно точно совпадать с именем, которое вы используете.
Пример. Использование неограниченного идентификатора
Эта ошибка может возникать, если идентификатор не является правильно заданной областью. Если вы видите C2065 при использовании cout , это является причиной. Если функции и операторы стандартной библиотеки C++ не полностью определены в пространстве имен или вы не std передали пространство имен в текущую область с помощью using директивы, компилятор не сможет их найти. Чтобы устранить эту проблему, необходимо либо полностью определить имена идентификаторов, либо указать пространство имен с помощью using директивы.
Этот пример не компилируется, поскольку cout и endl определены в std пространстве имен:
Идентификаторы, объявляемые внутри class типов, struct или enum class , также должны уточняться именем их включающей области при их использовании за пределами этой области.
Пример: предварительно скомпилированный заголовок не является первым
Этот пример не удается скомпилировать, поскольку cout и endl определены в < заголовке iostream >, который игнорируется, так как он включается перед предкомпилированным файлом заголовка. Чтобы выполнить сборку этого примера, создайте все три файла, а затем скомпилируйте файл stdafx. cpp, а затем скомпилируйте C2065_pch. cpp.
Пример: отсутствует заголовочный файл
Вы не включили заголовочный файл, объявляющий идентификатор. Убедитесь, что файл, содержащий объявление идентификатора, включен в каждый исходный файл, который его использует.
Другая возможная причина заключается в том, что при использовании списка инициализаторов не включается < заголовок initializer_list >.
эта ошибка может возникать в исходных файлах Windows классических приложений, если вы определяете VC_EXTRALEAN , WIN32_LEAN_AND_MEAN или WIN32_EXTRA_LEAN . Эти макросы препроцессора исключают некоторые файлы заголовков из Windows. h и afxv_w32. h для ускорения компиляции. Просмотрите Windows. h и afxv_w32. h, чтобы получить последние сведения о том, что исключено.
Пример: отсутствует закрывающая кавычка
Эта ошибка может возникать, если отсутствует закрывающая кавычка после строковой константы. Это простой способ запутывания компилятора. Обратите внимание, что пропущенная закрывающая кавычка может быть в нескольких строках перед сообщаемым расположением ошибки.
Пример. Использование итератора вне области действия цикла
Эта ошибка может возникать, если объявить переменную-итератор в for цикле, а затем попробовать использовать эту переменную итератора вне области for цикла. Компилятор включает параметр компилятора /Zc: forScope по умолчанию. Дополнительные сведения см. в разделе Поддержка итераторов отладки .
Пример: объявление удаленного препроцессора
Эта ошибка может возникать, если вы ссылаетесь на функцию или переменную, которая находится в коде, скомпилированном по условию, который не компилируется для текущей конфигурации. Это также может произойти при вызове функции в файле заголовка, который в настоящее время не поддерживается в среде сборки. Если определенные переменные или функции доступны только при определении конкретного макроса препроцессора, убедитесь, что код, вызывающий эти функции, может быть скомпилирован только при определении одного и того же макроса препроцессора. Эту ошибку легко выявить в интегрированной среде разработки, так как объявление функции недоступно, если требуемые макросы препроцессора не определены для текущей конфигурации сборки.
Это пример кода, который работает при сборке в отладке, но не в розницу:
Пример: сбой выведения типа C++/CLI
Эта ошибка может возникать при вызове универсальной функции, если аргумент предполагаемого типа не может быть выведен из используемых параметров. Дополнительные сведения см. в разделе универсальные функции (C++/CLI).
Пример: параметры атрибута C++/CLI
эта ошибка также может быть вызвана работой по согласованности компилятора, выполненной для Visual Studio 2005: проверка параметров для Visual C++ных атрибутов.
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 is not 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 using 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.
Example: use an unscoped identifier
This error can occur if your identifier is not properly scoped. If you see C2065 when you use cout , this is the cause. When C++ Standard Library functions and operators are not fully qualified by namespace, or you have not 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:
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 example fails to compile because cout and endl are defined in the header, which is ignored because it is included before the precompiled header file. To build this example, create all three files, then compile stdafx.cpp, then compile C2065_pch.cpp.
Example: missing header file
You have not 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.
Another possible cause is if you use an initializer list without including the header.
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 are missing a closing quote after a string constant. This is an easy way to confuse the compiler. Note that the missing closing quote may be several lines before the reported error location.
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. See Debug Iterator Support for more information.
Example: preprocessor removed declaration
This error can occur if you refer to a function or variable that is in conditionally compiled code that is not compiled for your current configuration. This can also occur if you call a function in a header file that is currently not 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, because the declaration for the function is greyed out if the required preprocessor macros are not defined for the current build configuration.
This is an example of code that works when you build in Debug, but not Retail:
Example: C++/CLI type deduction failure
This error can occur when calling a generic function, if the intended type argument cannot be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).
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.
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 is not 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 using 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.
Example: use an unscoped identifier
This error can occur if your identifier is not properly scoped. If you see C2065 when you use cout , this is the cause. When C++ Standard Library functions and operators are not fully qualified by namespace, or you have not 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:
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 example fails to compile because cout and endl are defined in the header, which is ignored because it is included before the precompiled header file. To build this example, create all three files, then compile stdafx.cpp, then compile C2065_pch.cpp.
Example: missing header file
You have not 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.
Another possible cause is if you use an initializer list without including the header.
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 are missing a closing quote after a string constant. This is an easy way to confuse the compiler. Note that the missing closing quote may be several lines before the reported error location.
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. See Debug Iterator Support for more information.
Example: preprocessor removed declaration
This error can occur if you refer to a function or variable that is in conditionally compiled code that is not compiled for your current configuration. This can also occur if you call a function in a header file that is currently not 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, because the declaration for the function is greyed out if the required preprocessor macros are not defined for the current build configuration.
This is an example of code that works when you build in Debug, but not Retail:
Example: C++/CLI type deduction failure
This error can occur when calling a generic function, if the intended type argument cannot be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).
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.
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 is not 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 using 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.
Example: use an unscoped identifier
This error can occur if your identifier is not properly scoped. If you see C2065 when you use cout , this is the cause. When C++ Standard Library functions and operators are not fully qualified by namespace, or you have not 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:
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 example fails to compile because cout and endl are defined in the header, which is ignored because it is included before the precompiled header file. To build this example, create all three files, then compile stdafx.cpp, then compile C2065_pch.cpp.
Example: missing header file
You have not 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.
Another possible cause is if you use an initializer list without including the header.
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 are missing a closing quote after a string constant. This is an easy way to confuse the compiler. Note that the missing closing quote may be several lines before the reported error location.
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. See Debug Iterator Support for more information.
Example: preprocessor removed declaration
This error can occur if you refer to a function or variable that is in conditionally compiled code that is not compiled for your current configuration. This can also occur if you call a function in a header file that is currently not 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, because the declaration for the function is greyed out if the required preprocessor macros are not defined for the current build configuration.
This is an example of code that works when you build in Debug, but not Retail:
Example: C++/CLI type deduction failure
This error can occur when calling a generic function, if the intended type argument cannot be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).
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.
Читайте также: