Thursday, February 18, 2010

GNU C++ compiler (g++) does not like the typical hello-world program


In some old text books or web sites, you can see the standard or traditional "hello world" program like this:
#include <iostream.h>
main()
{
   cout << "Hello World!" << endl;
}
If you use the latest GNU C++ compiler to build this program, you will get a warning.
$ g++ helloworld.cpp 
In file included from /usr/include/c++/4.2/backward/iostream.h:31,
                 from helloworld.cpp:1:
/usr/include/c++/4.2/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.
The executable is generated with the deprecated header. To get off the warning message, you should include <iostream> instead of <iostream.h>, as what the warning message suggests. It is important to use the new header if you are writing new code because the deprecated headers are for the backward compatibility of the old code and they may not be fully supported. Let us replace the header and re-compile.
#include <iostream>
main()
{
   cout << "Hello World!" << endl;
}
We are sorry to see that it gets worse. The compiler refuses to build the program.
$ g++ helloworld.cpp 
helloworld.cpp: In function 'int main()':
helloworld.cpp:4: error: 'cout' was not declared in this scope
helloworld.cpp:4: error: 'endl' was not declared in this scope
GNU C++ uses namespace to avoid naming collisions. 'cout' and 'end' are defined in the 'std' namespace. To use them, simply add the 'std' namespace to your program.
#include <iostream>
using namespace std;
main()
{
   cout << "Hello World!" << endl;
}
Now the code can be compiled. But they are not perfect yet. If you turn on all the warning options of g++, you can see there are still warnings.
$ g++ -Wall helloworld.cpp 
helloworld.cpp:3: warning: ISO C++ forbids declaration of 'main' with no type
GNU C++ encourages you to explicitly declare the main() function with a return type of int. So the final code will become:
#include <iostream>
using namespace std;
int main()
{
  cout << "Hello World!" << endl;
  return 0;
}
In conclusion, GNU C++ is stricter in the syntax. For an old program like in this example, we need to check three things.
  • Use the new C++ header;
  • Use the proper namespace;
  • Explicitly declare function type and explicitly return if the type is not 'void'.

No comments:

 
Get This <