LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Problem with hello world (https://www.linuxquestions.org/questions/linux-newbie-8/problem-with-hello-world-531172/)

gregorian 02-21-2007 07:03 PM

Problem with hello world
 
I ran this by using: gcc hello.cpp

Quote:

#include <iostream>

int main()
{
cout << "Hello World!" << endl;
return 0;
}
I got this error:

Quote:

hello.cpp: In function `int main()':
hello.cpp:5: `cout' undeclared (first use this function)
hello.cpp:5: (Each undeclared identifier is reported only once for each
function it appears in.)
hello.cpp:5: `endl' undeclared (first use this function)
I cant find any mistake in this simple program.

macemoneta 02-21-2007 07:26 PM

Take a look at this thread. In short:

Code:

$ cat hello.cpp
#include <iostream>

using std::cout;
using std::endl;

int main()
{
cout << "Hello World!" << endl;
return 0;
}


$ g++ hello.cpp
$


gregorian 02-21-2007 09:34 PM

Ah, that worked.Thanks for the link.

One question: Why should I insert "using namespace std"? Can't I just omit it? This program worked properly without it in windows.

macemoneta 02-21-2007 09:44 PM

From the link:

Quote:

this is why #include <stdlib> does not work in C++. The latest restandardization of C++ has a part that pretty much says that all the include files are antiquated. That's why <iostream.h> is <iostream>. With that came the changing of C headers. In this case, #include <stdlib.h> becomes <cstdlib>. Don't ask why, I don't know =].

As for 'cout undeclared', that's also because of the most recent restandardization. If your studies of C++, you'll eventually read about namespaces. Namespaces are more or less your own way of scoping variables. All of the built in classes (cout, cin, endl, vector, string, etc.) are in the namespace std. So to use them you have to use :: operator since all those classes are no longer in a global scope. (Ah OOP.... i hate it sometimes)

gregorian 02-21-2007 09:50 PM

Ok, Thank you for the help!


All times are GMT -5. The time now is 10:06 PM.