20

In my header file I'm getting the

error: ‘string’ has not been declared

error but at the top of the file I have #include <string>, so how can I be getting this error?

zahypeti
  • 183
  • 1
  • 8
neuromancer
  • 53,769
  • 78
  • 166
  • 223
  • 6
    err...source code please :) – Daniel Rodriguez May 23 '10 at 06:36
  • 1
    I had the issue that with `#include ` it doesn't work. There is no error on the include, but it says "error: ‘std::string’ has not been declared". After changing `` to ``, it works. – Luc Jul 14 '18 at 21:01

3 Answers3

44

string resides in the std namespace, you have to use std::string or introduce it into the scope via using directives or using declarations.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
5

Use

std::string var;

or

using namespace std;
string var;

String is in a std namespace so you must let your compiler know.

KamikazeCZ
  • 714
  • 8
  • 22
1

Most of the classes and class templates, and instances of those classes, defined by the Standard Library (like string and cout) are declared in the std:: namespace, not in the global namespace. So, whenever you want to use (say) string, the class is actually std::string.

You can add that namespace prefix explicitly every time you use such a class, but that can become tedious. In order to help, you can add using declarations for those classes you use frequently.

So, in your case, you could add lines like the following, generally somewhere shortly after the corresponding #include lines:

#include <string>
#include <iostream>

using std::string;
using std::cout; // Added as illustrative examples of other
using std::endl; // ... elements of the Standard Library

Or, if you have a compiler that supports the C++17 Standard (or later), you can put more than one class in the same statement:

using std::string, std::cout, std::endl; // C++17 or later

But, beware of using the generic, "cover-all" using namespace std; directive (even though that is actually valid C++ syntax). See: Why is "using namespace std;" considered bad practice?


For a more general introduction to, and overview of, the Standard Template Library (now, more correctly known as the C++ Standard Library), see the tag-Wiki for the tag.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83