LKBEN11116: Howto write a first version of Hello World with gcc under linux


This article has not been checked!

LKB | Created: 02/04/2020 | Version: 0 | Language: EN | Rating: 0 | Outdated: False | Marked for deletion: False

Author: Wim Peeters - Keskon GmbH & Co. KG


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)

About the Author

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 in different European countries and different European languages. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform where he is one of the most important contributors and the main developer.

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!