Problem when compiling C++ with g++!

Status
Not open for further replies.

Thomson

Full Member level 3
Joined
Oct 15, 2004
Messages
181
Helped
4
Reputation
8
Reaction score
1
Trophy points
1,298
Activity points
2,400
hi,
Although searched some websites and referred to some documents, the following problems remained unsolved yet!

Code:
#include <iostream>
#include <string>
  int main()
  {
      int errors = 0;
      string str("a very long literal string");
      for (int ix=0; ix <100000; ++ix)
      {
             int len = str.size();
             string str2 = str;
             if (str != str2) 
                   ++errors;
        }
    }
     cout << "string class: "
             << errors << "errors occured\n";
  }

when compiled with g++ under linux, the followng information occured:

"string" undeclared! and of course some other warnings related to this error!

And i checked the search library that the g++ used when searching the standard library doesn't contain the C++ standard library, which is under another directory!

However, when i modifed the first include file to "iostream.h", then /usr/lib/c++ library is searched which contains the C++ standard library.

Can anybody tell me how to solve this?


Thanks in advance!

Thomson
 

Can't remember, but doesn't g++ require you to link to the string file with something like "-l...." I will try to find out more for you.

Added after 15 minutes:

I think I found a partial solution.
You gotta use namespace
Code:
#include <string>
using namespace std;

int main()
{
   string = "Ogg Vorbis Rocks!";
   return 0;
}

or another alternative

Code:
#include <string>

int main()
{
   std::string name = "This forum is the best!";
   return 0;
}

These I found on the web...not my own code. Hope it works.
 

Using the namespace for C++ programs is a requirement by the compiler "g++" so you
will be explicitly telling the compiler about the specific class found in specific name
space.
For writing C programs this is not the requirement and code run normally without the use
of namespace.
In other words if you are porting some C++ code from some other compiler to run under
g++, you need to edit the code accordingly.
 

i think it will be better to use anno's second solution because using namespace std; include all the necessary libraries while std:: will tell the compiler to include only a specific respective library...
 

Try this. Aways specify the namespace in which the object definitions are defined.

#include <iostream>
#include <string>
int main()
{
int errors = 0;
std::string str("a very long literal string");
for (int ix=0; ix <100000; ++ix)
{
int len = str.size();
std::string str2 = str;
if (str != str2)
++errors;
}
}
std::cout << "string class: "
<< errors << "errors occured\n";
}
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…