There are several C++ compilers that we can choose from the Web. To make it easier for you to follow all the code in this book, I have chosen a compiler that will make the programming process simpler—definitely the easiest one. In this chapter, you will discover the following topics:
Setting up the MinGW compiler
Compiling in C++
Troubleshooting in GCC C++
This is the hardest part—where we have to choose one compiler over the others. Even though I realize that every compiler has its own strength and weakness, I want to make it easier for you to go through all the code in this chapter. So, I suggest that you apply the same environment that we have, including the compiler that we use.
I am going to use GCC, the GNU Compiler Collection, because of its widely used open source. Since my environment includes Microsoft Windows as the operating system, I am going to use Minimalistic GCC for Windows (MinGW) as my C++ compiler. For those of you who have not heard about GCC, it is a C/C++ compiler that you can find in a Linux operating system and it is included in a Linux distribution as well. MinGW is a port of GCC to a Windows environment. Therefore, the entire code and examples in this book are applicable to any other GCC flavor.
For your convenience, and since we use a 64-bit Windows operating system, we chose MinGW-w64 because it can be used for Windows 32-bits and 64-bits architecture. To install it, simply open your Internet browser and navigate to http://sourceforge.net/projects/mingw-w64/ to go to the download page, and click on the Download button. Wait for a moment until the mingw-w64-install.exe
file is completely downloaded. Refer to the following screenshot to locate the Download button:

Now, execute the installer file. You will be greeted by a Welcoming dialog box. Just press the Next button to go to the Setup Setting dialog box. In this dialog box, choose the latest GCC version (at the writing time this, it is 4.9.2), and the rest of the options are to be chosen, as follows:

Click on the Next button to continue and go to the installation location option. Here, you can change the default installation location. I am going to change the installation location to C:\MinGW-w64
in order to make our next setting easier, but you can keep this default location if you want.

Click on the Next button to go to the next step and wait for a moment until the files are downloaded and the installation process is complete.
Now you have the C++ compiler installed on your machine, but you can only access it from its installed directory. In order to access the compiler from any directory in your system, you have to set the PATH environment by performing the following steps:
Run Command Prompt as an administrator by pressing the Windows + R key. Type
cmd
in the text box and, instead of pressing the Enter key, press Ctrl + Shift + Enter to run the command prompt in Administrator mode. The User Account Control dialog box will then appear. Choose YES to confirm that you intend to run Command Prompt in Administrator mode. If you do this correctly, you will get a title bar labeled Administrator: Command Prompt. If you do not get it, you might not have the administrator privilege. In this case, you have to contact the administrator of your computer.Type the following command in Command Prompt in Administrator mode:
rundll32.exe sysdm.cpl,EditEnvironmentVariables
Press the Enter key and the command prompt will immediately run the Environment Variables window. Afterwards, go to System variables, select the variable named Path, click on the Edit button to open the Edit System Variable dialog box, and then append the last Variable value parameter with the following string:
;C:\MinGW-w64\mingw64\bin
(Otherwise, you will have to adjust the path of the installation directory if you use the default location the installation wizard is given in the previous step)
Click on the OK button on the Edit System Variable dialog box, and click on the OK button again in the Environment Variables dialog box to save these changes.
It is time to try our Environment Variable setting. Open a new Command Prompt window, either in Administrator or non-Administrator mode, in any active directory except C:\MinGW-w64
and type the following command:
g++ --version
You have configured the proper settings if you see the output informing you the following:
g++ (x86_64-posix-seh-rev2, Built by MinGW-W64 project) 4.9.2
If you are showed a different version number, you might have another GCC compiler on your computer. To solve this problem, you can modify Environment Variable and remove all path environment settings associated with the other GCC compiler, for instance, C:\StrawberryPerl\c\bin
.
However, if you do believe that you have followed all the steps correctly, but you still get an error message, as shown in the following snippet, you might have to restart your machine for your new system settings to be set:
'g++' is not recognized as an internal or external command, operable program or batch file.
Microsoft Windows has been equipped with Notepad, a simple text editor to create plain text files. You can use Notepad to create a C++ file, where the file must contain only plain text formatting. You can also turn to a heavy Integrated Development Environments (IDE) when you want to edit your code, but I prefer a simple, lightweight, and extensible programming plain-text editor, so I choose to use a text editor instead of IDE. Since I will need syntax highlighting when writing code to make it easier to read and understand, I pick Notepad++ as our text editor. You can choose your favorite text editor as long as you save the output file as plain text. Here is the sample of syntax highlighting in Notepad++:

If you decide to use Notepad++ as I did, you can go to http://notepad-plus-plus.org/ to grab the latest version of Notepad++. Find the Download menu on the main page and select the current version link. There, you will find a link to download the installer file. Use the Notepad++ Installer file instead of the package file to get the easiest way to set it up on your machine by following all the instructions on the installer wizard.

Now that we have our development ready, we can write our first C++ program. To keep it clean, create a CPP
folder in the C drive (C:\CPP
) to store our sample code. You can have the same directory location on your system in order to follow all the steps more conveniently. Otherwise, you will have to make a little bit of modification if you decide to use a different directory location.
We won't create the Hello World! program for our first example code. It is boring in my opinion and, by now, you should already know how to code the Hello World! program. We are going to create a simple random number generator. You can use this program to play with your friends. They have to guess which number will be displayed by the program. If the answer is incorrect, you can cross out his/her face with a marker and continue playing until you are not able to recognize your friend's face anymore. Here is the code to create this generator:
/* rangen.cpp */ #include <cstdlib> #include <iostream> #include <ctime> int main(void) { int guessNumber; std::cout << "Select number among 0 to 10:"; std::cin >> guessNumber; if(guessNumber < 0 || guessNumber > 10) { return 1; } std::srand(std::time(0)); int randomNumber = (std::rand() % (10 + 1)); if(guessNumber == randomNumber) { std::cout << "Congratulation, " <<guessNumber<<" is your lucky number.\n"; } else { std::cout << "Sorry, I'm thinking about number \n" << randomNumber; } return 0; }
Type the code in your text editor and save it with the name of the file rangen.cpp
in the C:\CPP
location. Then, open Command Prompt and point the active directory to the C:\CPP
location by typing the following command in Command Prompt:
cd C:\CPP
Next, type the following command in the console to compile the code:
g++ -Wall rangen.cpp -o rangen
The preceding command compiles the rangen.cpp
file with an executable file named rangen.exe
, which contains a bunch of machine code (the exe
extension is automatically added to indicate that this file is an executable file in Microsoft Windows). The output file for the machine code is specified using the -o
option. If you use this option, you have to specify the name of the output file as well; otherwise, the compiler will give you an error of a missing filename. If you omit both the -o
option and the output's filename, the output is written to a default file called a.exe
.
Tip
The existing executable file that has the same name as the compiled source file in the current directory will be overwritten.
I recommend that you use the -Wall
option and make it a habit since this option will turn on all the most commonly used compiler warnings. If the option is disabled, GCC will not give you any warning. Because our Random Number Generator code is completely valid, GCC will not give out any warnings while it is compiled. This is why we depend on the compiler warnings to make sure that our code is valid and is compiled cleanly.
To run the program, type rangen
in the console with the C:\CPP
location as the active directory, and you will be showed a welcoming word: Select number among 0 to 10. Do what it instructs you to and choose a number between 0
to 10
. Then, press Enter and the program will give out a number. Compare it with your own. If both the numbers are same, you will be congratulated. However, if your chosen number is different from the number the code generated, you will be informed the same. The output of the program will look as shown in the following screenshot:

Unfortunately, I never guessed the correct number in the three times that I tried. Indeed, it is not easy to guess which number the rand()
function has generated, even if you use a new seed every time the number is generated. In order to minimize confusion, I am going to dissect the rangen.cpp
code, as follows:
int guessNumber; std::cout << "Select number among 0 to 10: "; std::cin >> guessNumber;
I reserved a variable called guessNumber
to store the integer number from the user and used the std::cin
command to obtain the number that was input from the console.
if(guessNumber < 0 || guessNumber > 10) { return 1; }
If the user gives an out-of-range number, notify the operating system that there is an error that has occurred in the program—I sent Error 1, but in practice, you can send any number—and let it take care of the error.
std::srand(std::time(0)); int randomNumber = (std::rand() % (10 + 1);
The std::srand
function is used to initialize the seed, and in order to generate a different random number every time the std::rand()
function is invoked, we use the std::time(0)
function from the header ctime
. To generate a range of random numbers, we use the modulo
method that will generate a random number from 0 to (n-1) if you invoke a function like std::rand() % n
. If you want to include the number n as well, simply add n with 1
.
if(guessNumber == randomNumber) { std::cout << "Congratulation ,"<< guessNumber<<" is your lucky number.\n"; } else { std::cout << "Sorry, I'm thinking about number " << randomNumber << "\n"; }
Here is the fun part, the program compares the user's guessed number with the generated random number. Whatever happens, the user will be informed of the result by the program. Let's take a look at the following code:
return 0;
A 0
return tells the operating system that the program has been terminated normally and that there is no need to worry about it. Let's take a look at the following code:
#include <cstdlib> #include <iostream> #include <ctime>
Do not forget to include the first three headers in the preceding code since they contain the function that we used in this program, such as the time()
function is defined in the <ctime>
header, the srand()
function and the rand()
function are defined in the <cstdlib>
header, and the cout()
and cin()
functions are defined in the <iostream>
header.
If you find that it is hard to guess a number that the program has generated, this is because we use the current time as the random generator seed, and the consequence of this is that the generated number will always be different in every invocation of the program. Here is the screenshot of when I could guess the generated random number correctly after about six to seven attempts (for all the program invocations, we guessed the number incorrectly except for the last attempt):

Sometimes, we have to modify our code when it has bugs or errors. If we just make a single file that contains all the lines of code, we will be confused when we want to modify the source or it will be hard for us to understand the flow of the program. To solve the problem, we can split up our code into multiple files where every file contains only two to three functions so that it is easy to understand and maintain them.
We have already been able to generate random numbers, so now, let's take a look at the password generator program. We are going to use it to try compiling multiple source files. I will create three files to demonstrate how to compile multiple source files, which are pwgen_fn.h
, pwgen_fn.cpp
, and passgen.cpp
. We will start from the pwgen_fn.h
file whose code is as follows:
/* pwgen_fn.h */ #include <string> #include <cstdlib> #include <ctime> class PasswordGenerator { public: std::string Generate(int); };
The preceding code is used to declare the class name. In this example, the class name is PasswordGenerator
, and what it will do in this case is generate the password while the implementation is stored in the .cpp
file. The following is a listing of the pwgen_fn.cpp
file, which contains the implementation of the Generate()
function:
/* pwgen_fn.cpp */ #include "pwgen_fn.h" std::string PasswordGenerator::Generate(int passwordLength) { int randomNumber; std::string password; std::srand(std::time(0)); for(int i=0; i < passwordLength; i++) { randomNumber = std::rand() % 94 + 33; password += (char) randomNumber; } return password; }
The main entry file, passgen.cpp
, contains a program that uses the PasswordGenerator
class:
/* passgen.cpp */ #include <iostream> #include "pwgen_fn.h" int main(void) { int passLen; std::cout << "Define password length: "; std::cin >> passLen; PasswordGenerator pg; std::string password = pg.Generate(passLen); std::cout << "Your password: "<< password << "\n"; return 0; }
From the preceding three source files, we will produce a single executable file. To do so, go to Command Prompt and type the following command in it:
g++ -Wall passgen.cpp pwgen_fn.cpp -o passgen
I did not get any warning or error, so even you should not. The preceding command compiles the passgen.cpp
and pwgen_fn.cpp
files and then links them together to a single executable file named passgen.exe
. The pwgen_fn.h
file, since it is the header file that has same name as the source file, does not need to state the same in the command.
Here is what you will get if you run the program by typing the passgen
command in the console window; you will get a different password every time the program is run:

Now, it is time for us to dissect the preceding source code. We will start from the pwgen_fn.h
file, which only contains the function declaration, as follows:
std::string Generate(int);
As you can see from the declaration, the Generate()
function will have a parameter with the int
type and will return the std::string
function. We do not define a name for the parameter in the header file since it will be matched with the source file automatically.
Open the pwgen_fn.cpp
file, to see the following statement:
std::string PasswordGenerator::Generate(int passwordLength)
Here, we can specify the parameter name, which is passwordLength
. In this case, we can have two or more functions with the same name as long as they are in different classes. Let's take a look at the following code:
int randomNumber; std::string password;
I reserved the variable named randomNumber
to store random numbers generated by the rand()
function and the password
parameter to store the ASCII converted from the random number. Let's take a look at the following code:
std::srand(std::time(0));
The seed random srand()
function is the same as what we used in our previous code to generate a random seed. We used it in order to produce a different number every time the rand()
function is invoked. Let's take a look at the following code:
for(int i=0; i < passwordLength; i++) { randomNumber = std::rand() % 94 + 33; password += (char) randomNumber; } return password;
The for
iteration depends on the passwordLength
parameter that the user has defined. With the random number generator statement std::rand() % 94 + 33
, we can generate the number that represents the ASCII printable character based on its code from 33 to 126. For more detailed information about the ASCII code table, you can go to http://en.wikipedia.org/wiki/ASCII. Let's take a look at the following code:
#include "pwgen_fn.h"
The #include
header's single line will call all headers included in the pwgen_fn.h
file, so we do not need to declare the included header in this source file as follows:
#include <string> #include <cstdlib> #include <ctime>
Now, we move to our main entry code, which is stored in the passgen.cpp
file:
int passLen; std::cout << "Define password length: "; std::cin >> passLen;
First, the user decides how long a password he/she wants to have, and the program stores it in the passLen
variable:
PasswordGenerator pg; std::string password = pg.Generate(passLen); std::cout << "Your password: "<< password << "\n";
Then, the program instantiates the PasswordGenerator
class and invokes the Generate()
function to produce a password with the length that the user has defined before.
If you look at the passgen.cpp
file again, you will find that there is a difference between the two forms of the include statement #include <iostream>
(with angle brackets) and #include "pwgen_fn.h"
(with quotation marks). By using angle brackets in the #include
header statement, the compiler will look for the system header file directories, but does not look inside the current directory by default. With the quotation marks in the #include
header statement, the compiler will search for the header files in the current directory before looking in the system header file directories.
We can split up a large program into a set of source files and compile them separately. Suppose we have many tiny files and we just want to edit a single line in one of the files, it will be very time consuming if we compile all the files while we just need to modify a single file.
By using the -c
option, we can compile the individual source code to produce an object file that has the .o
extension. In this first stage, a file is compiled without creating an executable file. Then, in the second stage, the object files are linked together by a separate program called the linker. The linker combines all the object files together to create a single executable file. Using the previous passgen.cpp
, pwgen_fn.cpp
, and pwgen_fn.h
source files, we will try to create two object files and then link them together to produce a single executable file. Use the following two commands to do the same:
g++ -Wall -c passgen.cpp pwgen_fn.cpp g++ -Wall passgen.o pwgen_fn.o -o passgen
The first command, using the -c
option, will create two object files that have the same name as the source file name, but with different extensions. The second command will link them together and produce the output executable file that has the name stated after the -o
option, which is the passgen.exe
file.
In case you need to edit the passgen.cpp
file without touching the two other files, you just require to compile the passgen.cpp
file, as follows:
g++ -Wall -c passgen.cpp
Then, you need to run the linking command like the preceding second command.
As we discussed previously, a compiler warning is an essential aid to be sure of the code's validity. Now, we will try to find the error from the code that we created. Here is a C++ code that contains an uninitialized variable, which will give us an unpredictable result:
/* warning.cpp */ #include <iostream> #include <string> int main (void) { std::string name; int age; std::cout << "Hi " << name << ", your age is " << age << "\n"; }
Then, we will run the following command to compile the preceding warning.cpp
code:
g++ -Wall -c warning.cpp
Sometimes, we are unable to detect this error since it is not obvious at the first sight. However, by enabling the -Wall
option, we can prevent the error because if we compile the preceding code with the warning option enabled, the compiler will produce a warning message, as shown in the following code:
warning.cpp: In function 'int main()': warning.cpp:7:52: warning: 'age' may be used uninitialized in this function [-Wmaybe-uninitialized] std::cout << "Hi " << name << ", your age is " << age << "\n";]
The warning message says that the age
variable is not initialized in the warning.cpp
file on the line 7, column 52. The messages produced by GCC always have the file:line-number:column-number:error-type:message form. The error type distinguishes between the error messages, which prevent the successful compilation, and warning messages, which indicate the possible problems (but do not stop the program from compiling).
Clearly, it is very dangerous to develop a program without checking for compiler warnings. If there are any functions that are not used correctly, they can cause the program to crash or produce incorrect results. After turning the compiler warning option on, the -Wall
option catches many of the common errors that occur in C++ programming.
GCC supports
ISO C++ 1998, C++ 2003, and also C++ 2011 standard in version 4.9.2. Selecting this standard in GCC is done using one of these options: -ansi
, -std=c++98
, -std=c++03
, or –std=c++11
. Let's look at the following code and give it the name hash.cpp
:
/* hash.cpp */ #include <iostream> #include <functional> #include <string> int main(void) { std::string plainText = ""; std::cout << "Input string and hit Enter if ready: "; std::cin >> plainText; std::hash<std::string> hashFunc; size_t hashText = hashFunc(plainText); std::cout << "Hashing: " << hashText << "\n"; return 0; }
If you compile and run the program, it will give you a hash number for every plain text user input. However, it is little tricky to compile the preceding code. We have to define which ISO standard we want to use. Let's take a look at the following five compilation commands and try them one by one in our Command Prompt window:
g++ -Wall hash.cpp -o hash g++ -Wall -ansi hash.cpp -o hash g++ -Wall -std=c++98 hash.cpp -o hash g++ -Wall -std=c++03 hash.cpp -o hash g++ -Wall -std=c++11 hash.cpp -o hash
When we run the first four preceding compilation commands, we should get the following error message:
hash.cpp: In function 'int main()': hash.cpp:10:2: error: 'hash' is not a member of 'std' std::hash<std::string> hashFunc; hash.cpp:10:23: error: expected primary-expression before '>' token std::hash<std::string> hashFunc; hash.cpp:10:25: error: 'hashFunc' was not declared in this scope std::hash<std::string> hashFunc;
It says that there is no hash
in the std
class. Actually, this is not true as a hash has been defined in the header <string>
since C++ 2011. To solve this problem, we can run the last preceding compilation command, and if it does not throw an error anymore, then we can run the program by typing hash
in the console window.

As you can see in the preceding screenshot, I invoked the program twice and gave Packt and packt as the input. Although I just changed a character, the entire hash changed dramatically. This is why hashing is used to detect any change in data or a file if they are transferred, just to make sure the data is not altered.
For more information about ISO C++11 features available in GCC, go to http://gcc.gnu.org/projects/cxx0x.html. To obtain all the diagnostics required by the standard, you should also specify the -pedantic
option (or the -pedantic-errors
option if you want to handle warnings as errors).
GCC provides several help and diagnostic options to assist in troubleshooting problems with the compilation process. The options that you can use to ease your troubleshooting process are explained in the upcoming sections.
Use the help
options to get a summary of the top-level GCC command-line options. The command for this is as follows:
g++ --help
To display a complete list of the options for GCC and its associated programs, such as the GNU Linker and GNU Assembler, use the preceding help
option with the verbose (-v
) option:
g++ -v --help
The complete list of options produced by the preceding command is extremely long—you may wish to go through it using the more
command or redirect the output to a file for reference, as follows:
g++ -v --help 2>&1 | more
You can find the version number of your installed GCC installation using the version
option, as shown in the following command:
g++ --version
In my system, if I run the preceding command, I will get an output like this:
g++ (x86_64-posix-seh-rev2, Built by MinGW-W64 project) 4.9.2
This depends on your setting that you adjust at the installation process.
The version number is important when investigating compilation problems, since older versions of GCC may be missing some features that a program uses. The version number has the major-version.minor-version
or major-version.minor-version.micro-version
form, where the additional third "micro" version number (as shown in the preceding command) is used for subsequent bug fix releases in a release series.
The -v
option can also be used to display detailed information about the exact sequence of commands that are used to compile and link a program. Here is an example that shows you the verbose compilation of the hello.cpp
program:
g++ -v -Wall rangen.cpp
After this, you will get something like this in the console:
Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=C:/mingw-w64/bin/../libexec/gcc/x86_64-w64-mingw32/4.9.2/lto-wrapper.exe Target: x86_64-w64-mingw32 Configured with: ../../../src/gcc-4.9.2/configure – ...Thread model: posix gcc version 4.9.2 (x86_64-posix-seh-rev2, Built by MinGW-W64 project) ...
The output produced by the -v
option can be useful whenever there is a problem with the compilation process itself. It displays the full directory paths used to search for header files and libraries, the predefined preprocessor symbols, and the object files and libraries used for linking.
We successfully prepared the C++ compiler and you learned how to compile the source code file you created using the compiler. Do not forget to use the -Wall
(Warning All) option every time you compile the source code because it is important to avoid a warning and subtle error. Also, it is important to use the -ansi
and -pedantic
options so that your source code is able to be compiled in any compiler, as it will check the ANSI standard and reject non-ISO programs.
Now, we can go to the next chapter to learn the networking concept so that you can understand network architecture in order to ease your network application programming process.