LKBEN11116: Howto write a first version of Hello World with gcc under linux in C++.


Symptom

You would like to start from the beginning and write your first programm with free software

Cause

none

Solution

To write a HelloWorld application with gcc you need to create a file with your prefered editor.

You safe the file as HelloWorld.cpp. The contents is shown below.

 


#include <iostream>

#include <ostream>



int main(void)

{

  ::std::cout << "Hello world!" << '\n';

}

Here you use the namespace std without a using statement first. As an alternative you could write the following, which is exactly the same:


using namespace std;



int main(void)

{

  cout << "Hello world!" << '\n';

}


Here the namespace std will be used so the cout does not have to be prefixed with ::std to use it. I think this is easier to read than the previous example.

To compile this file you open a shell (in use the bash shell) and enter the g++ command followed by the filename.

g++ HelloWorld.cpp

This will create a file named "a.out" which is the executable that has been created. To run this you type:

./a.out

Which will show "Hello wordl!" on the screen.

Do NOT use gcc because it will try to create a c and not a c++ application. This will result in errors.

To create a nicer name for your application you can tell g++ to create on with the -o parameter.

g++ HelloWorld.cpp -o helloworld

Now your application is named helloworld.

When this little program runs, you can take whichever C++ book from the shelf and start programming. Creating a GUI (grafical user interface) application is a bit more complex and not platform independant. (Here Java goes further than C/C++ by defining a standard GUI library wich C/C++ does not have)

 

Disclaimer:

The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!

About the Author

Author: Wim Peeters - Keskon GmbH & Co. KG

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience, including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform.

Latest update: 27-01-2023