Programming in C++
Lab 1: Introduction to language and tools
General overview of the language
C++ is a general purpose programming language, which is mainly used for developing system software (operating systems, drivers, office software, games et cetera). C++ is a compiled language, which means that the source code is turned into executable machine code. The compiled programs tend to have higher performance, but the downside is that the program needs to be recompiled for each platform (ex. Windows EXE-files do not run on Linux platform). C++ is a superset of the language C, therefore C programs can generally be compiled with C++ compilers. C++ is also one of the predecessor languages to Java.
C++ language is specified by the standard ISO/IEC 14482, which specifies the requirements for interfaces the compilers should use. At the same time the standard does not determine how the language constructions need to be implemented. At the time of writing the materials for this course the latest C++ standard (C++14) was released at the end of 2017. There is a sub-committee in ISO for C++ standards.
The providers of compilers usually need time to be able to support all the requirements specified by the standards. Currently C++11 (standard ratified in 2011) is the main widely supported version.
Program structure and compiling
The source code is divided to header files and code files. In C++ programs all elements used
(variables, functions et cetera) must be predefined. Headers are files, where all the declarations
(element and attribute descriptions) are collected. By default the code, which is run, is
kept in code files and not in header files. To use the functions and variables defined in the header
files, source code files must refer to them. The most common filename extension for C++ is cpp
, but
cc
is also used. The extension for headers is usually h
(e.g.: ‘queue.h
’).
Compiling a C++ program consists of several steps. Simplified, the steps are as follows:
- For every code file (
cpp
):- During preprocessing the used headers are copied into the code.
- During compiling syntax errors, if any, are found. If there are none then an object file is generated (consisting mostly of machine code, but also information which allows a linker to do its job).
- All the generated object files are then linked together and the dependencies between functions are checked. Linking errors „
undefined reference
“ refer to the fact that the function declaration could be found, but not its content from any of the object files.
Tools
The most important tool is the compiler. The compiler usually also contains a pre-processor and a linker. In our labs we use GCC (GNU C/C++ Compiler) and clang compilers. On most of the UNIX systems there is GCC installed from the start. clang is mostly used on Mac OS X, where it is shipped together with Xcode IDE (integrated development environment). clang is also gaining popularity on other systems thanks to its better code analysis and clearer error messages. GCC for Windows can be found for example in MinGW and Cygwin. Both have their pros and cons – MinGW is more compatible with Windows, Cygwin is a better emulator of UNIX-type systems. For this course we have mainly worked with MinGW.
The GCC C++ compiler can be run with command g++
. For the Clang C++ compiler, the command is clang++
.
Another important tool for C++ programmer is the debugger. Debugger can be used to follow the
programs execution process and see the data during the execution. It is used to search for bugs and to
understand the programs better. The classical command line debugger is gdb. With clang, the
included debugger is lldb.
For documenting the programs we use a tool called Doxygen, which together with a special syntax turns comments in source and header files into a program’s documentation. Documenting the programs using Doxygen is required for several home exercises.
To organize and automate the compilation process we use a tool named make, which also is included in most of the UNIX-based systems standard tools. Make helps to set the relations between headers, source code, object files and the final program.
There are several alternatives and competitors for Make – autoconf, cmake, jam, Boost.Build etc. Some of them generate project files for different IDE’s and some replace make in general.
One very important tool for complex systems developers is Valgrind. Valgrind helps the developers find mistakes in memory usage and to find complex bugs in unexpectedly crashing programs. We recommend you to get used to that program.
The following editors and IDES, amongst others, should be noted:
- Microsoft Visual C++ 2013 Express – uses Microsoft compiler. Not used in this course, but a good IDE;
- Eclipse CDT – C++ extenstions for Eclipse;
- Qt Creator – a good environment to create graphical user interfaces for programs depending on Qt, a good multiplatform tool in general;
- Xcode – Mac OS X / iOS development environment for several programming languages (including Objective-C), uses clang compielr;
- Code::Blocks – IDE supporting gcc and gdb for Windows, Linux and Mac OS X;
- KDevelop, Anjuta, etc – freely distributed IDEs, which are also available for several platforms;
- CLion - C and C ++ IDE from JetBrains.
- Visual Studio Code - a text editor that can be successfully extended to a full-fledged C++ evelopment tool.
- vim, emacs, etc – text editors suitable for working in text mode (on terminal).
Your (maybe) first C++ program
#include <iostream> /* Input/output header */ #include <cstdlib> /* EXIT_SUCCESS constant */ using namespace std; /* Namespace (to be explained) */ int main () { /* Main function */ cout << "Hello, world!" << endl; /* Output */ return EXIT_SUCCESS; /* Return value */ }
Data types, variables and arrays
A quick overview of the main data types and the definition of variables in C ++.
Type | Example | Explanation |
---|---|---|
char | char x = 7; char a = 'C'; | single-byte integer / character |
short | short port = 80; | at least a two-byte integer |
int | int i = 0; | an integer of at least four bytes |
long | long id = 42534323; | an integer of at least four bytes |
long long | long long h = 100ULL; | an integer of at least eight bytes |
float | float pi = 3.14159F; | floating point number |
double | double delta = 0.000001; | double precision floating point number |
long double | long double d = 2.0e5; | floating point number with maximum accuracy |
bool | bool ok = false; | true value |
Type void
indicates no type. Integers are signed by default (for example, the char
range is -128 to 127). If we only want non-negative numbers, we need to add a type specification unsigned
. For example, an unlabeled double-byte integer would range from 0 to 65535. A signed integer would range from -32768 to 32767.
Note: In the case of the char type, it is worth noting that the corresponding character is written on the screen instead of the number (for example, char x = 65; cout << x; the letter 'A' is output as a result).
C arrays start with an index of 0. Thus, if you define an array with 50 elements, their indices range from 0 to 49. Arrays can be multidimensional. Dimensions are global across an array: for example, a table row always has as many elements as the array should have by definition.
Attention! C ++ does not check the indexes of arrays, so the programmer must do it himself!
Arrays of char
type (character sequences) that can be used to represent words are treated separately . NB! Since the nil symbol at the end of a word is also a character, a word of up to 99 characters can be stored inside a 100-element array. There is also an easier way to process words in C ++ - a class string
, but we will deal with this in the following workshops.
Definition | Explanation |
---|---|
int tripstrapstrull [3] [3]; | 3x3 matrix, indices [0] [0] to [2] [2] |
char buffer [100]; | a word of up to 99 characters or an array of 100 characters |
string list [30]; | A 30-element word array |
double polynomial [16]; | A 16-element array of floating point numbers |
Functions
Subroutines (function) must have a data type specified, which is the return value. If we do not want the function to return a value, we set it as the data type void
. The list of arguments is appended in parentheses after the function name.
Examples of functions are given in the table below:
Function declaration | Explanation |
---|---|
long min (long a, long b); | a function with two long type arguments that returns a long type value |
float calculate_square (float x); | a function with a float type argument that returns a float type value |
int get_error_code (); | a function without arguments that returns a value of type int |
void do_stuff (); | an argument-free function that returns nothing |
int main (int argc, char * argv []); | a function with an array type argument that returns an int type value |
Example of a program with multiple code files
File: functions.h
/* This function returns the smaller of the two inputs. The header contains a declaration of this function. */ long minimum (long a, long b);
File: functions.cpp
/* This function returns the smaller of the two inputs. The CPP file contains actual code. */ #include "functions.h" /* If a function uses another function, */ /* the declaration must come before the use. */ long minimum (long a, long b) { if (a > b) return b; else return a; }
File: main.cpp
/* This is the main program. Execution begins with the 'main' function. */ #include <iostream> /* Input/output header */ #include <cstdlib> /* EXIT_SUCCESS constant*/ #include "functions.h" /* Our function */ using namespace std; /* Namespace (to be explained) */ int main(int argc, char *argv[]) { cout << "min (35, 40) = " << minimum (35, 40) << endl; return EXIT_SUCCESS; }
File: Makefile
# To compile, run 'make' in the same directory as this file # Declare the name of our program (in Windows, the compiler adds .exe) PROGRAM = program # The needed object files (we make these from the source code) OBJ = main.o functions.o # Compiler flags (-Wall shows all warnings when compiling, always use this!) CFLAGS = -Wall # This is the first target. It will be built when you run 'make' or 'make all' all: $(PROGRAM) # Rule for linking IMPORTANT! The space in front of $(CXX) is a TABULATOR! $(PROGRAM): $(OBJ) $(CXX) $(OBJ) -o $(PROGRAM) # Rules for compiling main.o: main.cpp $(CXX) -c main.cpp -o main.o $(CFLAGS) functions.o: functions.cpp $(CXX) -c functions.cpp -o functions.o $(CFLAGS)
Reading command line parameters
You need to be able to read command line parameters to do your homework.
#include <iostream> /* As before */ #include <cstdlib> /* C library (for converting numbers)*/ #include <cstring> /* strcmp function*/ #include "functions.h" /* Our function */ using namespace std; int main(int argc, char *argv[]) { if (argc != 4) { /* Check if there are enough parameters */ cerr << "Error: Wrong number of command line parameters!" << endl; return EXIT_FAILURE; } long a = atol (argv[1]); /* Convert text to number */ long b = atol (argv[2]); if (strcmp (argv[3], "minimum") == 0) cout << "min (" << a << ", " << b << ") = " << minimum (a, b) << endl; return EXIT_SUCCESS; }
It is important to remember that a program always has at least one command line parameter. The first parameter is its name (in this case "program
"). That is why in the example we check that there are exactly 4 parameters (in some parts of the homework it may be necessary to cope with a different number of parameters).
Read about C ++ input / output here: http://www.cppreference.com/cppio/index.html
Description of atol
: http://www.cppreference.com/stdstring/atol.html
Word Comparison: http://en.cppreference.com/w/c/string/byte/strcmp
Materials
References to materials (books and websites) can be found on the module's website.