1/9

1. Introduction

First program in C++

File naming convention

C code files are text files. Conventionally, various extensions are used to designate file containing C code such as name.c, name.cc, name.cxx, name.cpp. [1]

C++ code also requires the so-called header files. Similarly, we find conventionally the following extensions name.h, name.hh, name.hxx, name.hpp.

We will use in the following examples the .cpp and .hpp convention. Note that there is no unique rule, the main good practice to be followed is to be coherent through your project.

First Hello World

Minimalistic code

A first classical minimalistic C++ code is the following

#include <iostream>

int main()
{
    std::cout << "Hello world" << std::endl;

    return 0;
}


  • #include <iostream>

    • Include the use of function of Input/Output from the standard library (iostream = Input Output Stream).

    • Note that standard C++ library header files conventionally don’t have extensions.

  • int main()

    • Entry point of the executable. All executable program must have one (and only one) function called main where the execution will start.

  • std::cout << "Hello World" << std::endl;

    • std :: cout << : common syntax to display text (here "Hello World") on the command line

      • cout means Common Output. By default it refers to the command line, excepted if redirected.

      • std::cout is the full name of an object which is in the namespace std (standard library).

      • :: is called the scope resolution operator.

      • << is a C++ operator. In this case, used to send the string information to the object std::cout.

    • << std::endl Add an new line after the text. endl refers to end of line.

  • return 0;

    • Integer values returned to the calling process. Typically the shell from the command line. Conventionnaly following C standard, 0 value indicates a program terminating without error.


Compiling the code

C code has to be compiled into an executable file before being run. There exists several C compilers depending on your platform. In Unix system, there is two common Open Source compilers handling C++ language

  • GCC, the historical GNU compiler project

  • Clang, a more recent Open Source project based on LLVM tool chain.


Example of compilation and execution

  • Using gcc

$ g++ main.cpp
$ ./a.out

a.out is the default name given to the generated executable when no one is explicitly provided.

  • Using clang

$ clang++ main.cpp
$ ./a.out
Compiler arguments

In development situation, we will usually use the following arguments

  • -g : Activate debuging information

  • -Wall -Wextra : Activate warning messages

  • -O2 : Allow compiler to perform optimization

We will further indicate explicitly the name of the output using the argument -o outputName. As a result, the common compilation command line for a single file will be

$ g++ main.cpp -o pgm -g -O2 -Wall -Wextra

or similarly with clang

$ clang++ main.cpp -o pgm -g -O2 -Wall -Wextra

In the case of executable file called pgm. The resulting executable can be called

$ ./pgm

std namespace

All objects and functions from the standard library are placed in the namespace std. This allows to define new objects or function with similar name. For example std::cos and myLib::cos may call two different implementation of the function called cos.

When using some objects/functions often X, it is possible to avoid typing every time std::X in using the syntax using std::X; before its use.

For instance, the previous program could have been written as follows

#include <iostream>

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

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

The use of using std::X; directive is a matter of personal choice. Note that the use of std:: in front of functions may help your IDE to autocomplete your typing. In this tutorial, std:: will be explicitly used at each function.


Note on using namespace std;

  • It is possible to insert all objects and functions from a given namespace into the global scope using the directive using namespace.

  • You may find on various internet examples the use of using namespace std; in beginning of files to avoid the use of std::.

⇒ This is considered as bad practice (ex.) and you should avoid using this directive [2]

  • The standard library may contains large number of objects and functions that may be platform and version dependant. Include all of their names in the global scope results in a so called namespace pollution and can result in name collision with other objects. For instance, your code may compile on your machine, but not on another one with another system.

Modern C++

C has a long history since its creation in 1985. Initially created as an extension of C programming language, modern C can be used is a large variety of ways.

C++ is standardized (ISO/IEC) since 1998 and has received several new impacting changes in the few recent years.

  • The basic common C syntax is available in the version _C98_

  • New modern syntax has been made available more recently with the version C11_, and shortly followed by _C14, C++17.

Currently, recent compilers have, by default, _C14_ version activated, and may compile, on demand, to other standard version. In gcc and clang, setting the C version can be made by the following argument

  • -std=

    • c++98

    • c++03

    • c++11 (or c++0x)

    • c++14 (or c++1y)

    • c++17 (or c++1z)

Good use of modern C++ syntax can bring cleaner syntax and more readable code (as well as other more technical possibilities) without requiring dynamic evaluation (zero cost overhead in comparison to dynamic languages with similar syntax).

We will suppose in this tutorial that programs are compiled using C++14 standard. [3]


Examples of use of some functionality of modern C++ (make sure you can compile, execute, and understand roughly what these codes are doing).

#include <iostream>

int main()
{
    auto list = {1.1, 5.7, 6.5, 7.2, -12.1, 6.3};

    for(auto element : list)
        std::cout << element << std::endl;

    return 0;
}
  • auto Modern C++ doesn’t require explicit type definition when the compiler can automatically deduct it (in this case, an initializer_list of double).

  • for(auto element : list) { …​ } Allows to loop over all elements of a container.


#include <iostream>
#include <string>
#include <map>


int main()
{
    std::map<std::string,double> menu = { {"fries",5.5},
                                          {"cheeseburger",8.0},
                                          {"salad",7.5},
                                          {"ice cream",5.0} };

    menu["limonade"] = 3.0;

    for( auto element : menu ) {
        auto [plate, price] = element;
        std::cout << "Price of " << plate << " is " << price <<" euros." << std::endl;
    }

    return 0;
}
  • std::string is the common type from the standard library to manage characters strings.

  • auto [plate, price] = element; Allows to receive assign different variables from tuples (here a string and a double value). Note that this code requires to be compiled using C++17.


1. Note that .cc, .cxx, .cpp have the advantage to differentiate C code file from C++ code file
2. at least not in the beginning of a file, and even less in a header file.
3. Note that you may encounter during internships, or future works, companies that will be constrained to work on old C++ version for compatibility with pre-existing code structure