Beginning C++ - C++ Recipes: A Problem-Solution Approach (2015)

C++ Recipes: A Problem-Solution Approach (2015)

CHAPTER 1

image

Beginning C++

The C++ programming language is a powerful low-level language that allows you to write programs that are compiled into machine instructions to be executed on a computer’s processor. This makes C++ different from newer languages such as C# and Java. These languages are interpreted languages. This means they are not executed directly on the processor but instead are sent to another program that is responsible for operating the computer. Java programs are executed using the Java virtual machine (JVM), and C# programs are executed by the Common Language Runtime (CLR).

Thanks to C++ being a language that is compiled ahead of time, it still finds wide use in fields where absolute performance is paramount. The most obvious area where C++ is still the most predominantly used programming language is the video game industry. C++ allows programmers to write applications that take full advantage of the underlying system architecture. You might become familiar with phrases such as cache coherency while pursuing a career as a C++ programmer. There aren’t many other languages that allow you to optimize your applications to suit the individual processors that your program is being designed to run on. This book introduces you to some of the pitfalls that can affect the performance of your applications at different times and shows you some techniques to tackle those issues.

Modern C++ is in a period where the language is seeing continual updates to its features. This has not always been the case. Despite being around since the early 1980s the C++ programming language was only standardized in 1998. A minor update and clarification of this standard was released in 2003 and is known as C++03. The 2003 update did not add any new features to the language however it did clarify some of the existing features that had gone overlooked. One of these was an update to the standard for the STL vector template to specify that the members of a vector should be stored contiguously in memory. The C++11 standard was released in 2011 and saw a massive update to the C++ programming language. C++ gained features for generalized type deduction system outside of templates, lambda and closure support, a built-in concurrency library and many more features. C++14 brings a smaller update to the language and generally builds upon the features already supplied by C++14. Features such as auto return type deduction from functions have been cleaned up, lambdas have been updated with new features and there are some new ways to define properly typed literal values.

This book strives to write portable, standards compliant C++14 code. At the time of writing it’s possible to write C++14 code on Windows, Linux and OS X machines so long as you use a compiler that provides all of the language features. To this end, this book will use Clang as the compiler on Windows and Ubuntu and will use Xcode on OS X. The rest of this chapter focuses on the software you need to write programs in C++ before showing you how to acquire some of the more common options available for Windows, OS X, and Linux operating systems.

Recipe 1-1. Finding a Text Editor

Problem

C++ programs are constructed from lots of different source files that must be created and edited by one or more programmers. Source files are simply text files, which usually come in two different types: header files and source files. Header files are used to share information about your types and classes between different files, and source files are generally used to contain the methods and the actual executable code that makes up your program.

Solution

A text editor then becomes the first major piece of software you require to begin writing C++ programs. There are many excellent choices of text editors available on different platforms. My best two picks at the moment are the free Notepad++ for Windows and Sublime Text 2, which despite not being free is available on all major operating systems. Figure 1-1 shows a screenshot from Sublime Text 2. Vim and gvim are also very good options that are available for all three operating systems. These editors provide many powerful features and are excellent choices for someone willing to learn.

9781484201589_Fig01-01.jpg

Figure 1-1. A screenshot from the Sublime Text 2 Editor

Image Note Don’t feel the urge to grab a text editor straight away. Some of the recipes later in this chapter cover integrated development environments (IDEs) that include all the software you need to write, build, and debug C++ applications.

Figure 1-1 shows one of the most important features of a good text editor: it should be able to highlight the different types of keywords in your source code. You can see in the simple Hello World program in Figure 1-1 that Sublime Text 2 is capable of highlighting the C++ keywordsinclude, int, and return. It has also added different-colored highlights to the main function name and the strings <iostream> and "Hello World!". Once you have some experience writing code with your text editor of choice, you will become adept at scanning your source files to zero in on the area of code you are interested in, and syntax highlighting will be a major factor in this process.

Recipe 1-2. Installing Clang on Ubuntu

Problem

You would like to build C++ programs that support the latest C++14 language features on a computer system running Ubuntu.

Solution

The Clang compiler supports all of the latest C++14 language features and the libstdc++ library supports all of the C++14 STL features.

How It Works

The Ubuntu operating system comes configured with package repositories that allow you to install Clang without much difficulty. You can achieve this using the apt-get command in a Terminal window. Figure 1-2 shows the command that you should enter to install Clang.

9781484201589_Fig01-02.jpg

Figure 1-2. An Ubuntu Terminal window showing the command needed to install Clang

To install Clang you can enter the following command on the command line sudo apt-get install clang. Running this command will cause Ubuntu to query its repositories and work out all of the dependencies needed to install Clang. You will be prompted once this process has been completed to confirm that you wish to install Clang and its dependencies. You can see this prompt in Figure 1-3.

9781484201589_Fig01-03.jpg

Figure 1-3. The apt-get dependency confirmation prompt

At this point you can hit enter to continue as yes is the default option. Ubuntu will then download and install all of the software needed for you to be able to install Clang on your computer. You can confirm that this has been successful by running the clang command. Figure 1-4 shows what this should look like if everything was successful.

9781484201589_Fig01-04.jpg

Figure 1-4. A successful Clang installation in Ubuntu

Recipe 1-3. Installing Clang on Windows

Problem

You would like to build C++14 based programs on the Windows operating system.

Solution

You can use Cygwin for Windows to install Clang and build applications.

How It Works

Cygwin provides a Unix-like command line environment for Windows computers. This is ideal for building programs using Clang as the Cygwin installed comes pre-configured with package repositories that include everything you need to install and use Clang on Windows computers.

You can get a Cygwin installer executable from the Cygwin website at http://www.cygwin.com. Be sure to download the 32bit version of the Cygwin installer as the default packages supplied by Cygwin currently only work with the 32bit environment.

Once you have downloaded the installer you should run it and click through until you are presented with the list of packages to install. At this point you want to select the Clang, make and libstdc++ packages. Figure 1-5 shows the Cygwin installer with the Clang package selected.

9781484201589_Fig01-05.jpg

Figure 1-5. Filtering the Clang package in the Cygwin installer

Packages can be marked for installation in the installer by clicking on the Skip area on the line for the package. Clicking skip once moves the package version to the latest. You should select the latest packages for Clang, make and libstdc++. Once you have selected all 3 you can click Next to be taken to a window asking to confirm the installation of the dependencies needed by these three packages.

Once you have successfully downloaded and installed all of the packages that you needed to be able to run Clang you can check that it was successful by opening a Cygwin terminal and typing the clang command. You can see the result of this output in Figure 1-6.

9781484201589_Fig01-06.jpg

Figure 1-6. Successfully running Clang in a Cywgin environment in Windows

Recipe 1-4. Installing Clang on OS X

Problem

You would like to build C++14 based programs on a computer running OS X.

Solution

Apple’s Xcode IDE comes with Clang as its default compiler. Installing Xcode from the OS X App Store also installs Clang.

How It Works

Install the latest version of Xcode from the App Store on your OS X computer. Once you’ve installed Xcode you can open a Terminal window using Spotlight and type clang to see that the compiler has been installed. Figure 1-7 shows how this should look.

9781484201589_Fig01-07.jpg

Figure 1-7. Running Clang on OS X after installing Xcode

Recipe 1-5. Building Your First C++ Program

Problem

You would like to use your computer to generate executable applications from C++ source code that you write.

Solution

Generating executables from a C++ source file involves two steps; compiling and linking. The steps undertaken in Recipe 1-2, Recipe 1-3 or Recipe 1-4 depending on your operating system will have resulted in you having all of the software you need to build applications from C++14 source files. You are now ready to build your first C++14 program. Create a folder to contain you project and add a text file named HelloWorld.cpp. Enter the code from Listing 1-1 into the file and save.

Listing 1-1. Your first C++14 Program

#include <iostream>

#include <string>

int main(void)
{
using namespace std::string_literals;

auto output = "Hello World!"s;
std::cout << output << std::endl;

return 0;
}

The code in Listing 1-1 is a C++ program that will only compile when using a C++14 compatible compiler. The Recipes 2-4 in this chapter contain instructions on how you can obtain a compiler that can be used to compile C++14 code for Windows, Ubuntu and OS X. You can build a working application once you have created a folder and the source file containing the code in Listing 1-1. You do this using a makefile. Create a file named makefile in the folder alongside your HelloWorld.cpp file. The makefile should not have a file extension which may seem a little strange to developers used to the Windows operating system however this is completely normal for Unix based operating systems such as Linux and OS X. Enter the code from Listing 1-2 into your makefile.

Listing 1-2. The makefile Needed to Build the Code in Listing 1-1

HelloWorld: HelloWorld.cpp
clang++ -g -std=c++1y HelloWorld.cpp -o HelloWorld

Image Note The whitespace before the clang++ command in Listing 1-2 is a tab. You cannot replace the tab with spaces as make will fail to build. Ensure that your recipes in a makefile always begin with tabs.

The text in Listing 1-2 consists of the instructions needed to build an application from your HelloWorld.cpp source file. The first word on the first line is the name of the target of the makefile. This is the name that the application executable will be given when the building process has been completed. In this case we will be building an executable named HelloWorld. This is followed by the prerequisites needed to build the program. Here you have listed HelloWorld.cpp as the only prerequisite as it is the only source file used to build the executable.

The target and prerequisites are then followed by a list of recipes that are carried out in order to build your application. In this small example you have a line that invokes the clang++ compiler to generate executable code from the HelloWorld.cpp file. The parameter passed to clang++using –std=c++1y asks Clang to build using the C++14 language standard and the –o switch specifies the name of the object output file generated by the compilation process.

Browse to the folder you created to store the source file and makefile using a command shell such as cmd on Windows or Terminal on Linux or OS X and type make. This will invoke the GNU make program and will automatically read and execute your makefile. This will output an executable file into the same folder that you can then run from the command line. You should be able to do this now and see that the text Hello World is output on your command line. Figure 1-8 shows what this would look like in an Ubuntu Terminal window.

9781484201589_Fig01-08.jpg

Figure 1-8. The Output Generated by Runnung HelloWorld in an Ubuntu Terminal

Recipe 1-6. Debugging C++ programs using GDB in Cygwin or Linux

Problem

You are writing a C++14 program and would like to be able to debug the application from the command line.

Solution

Both Cygwin for Windows and Linux based operating systems like Ubuntu can install and use the GDB command line debugger for C++ applications.

How It Works

You can use the Cygwin installer for Windows or the Package Manager installed with your favorite Linux distribution to install the GDB debugger. This will give you a command line C++ debugger that can be used to inspect the functionality of your C++ programs. You can practice this using the source, makefile and application generated as part of Recipe 1-5. To generate debugging information for your program you should update the makefile to contain he contents of Listing 1-3 and run make to generate a debuggable executable file.

Listing 1-3. A makefile to Generate a Debuggable Program

HelloWorld: HelloWorld.cpp
clang++ -g -std=c++1y HelloWorld.cpp -o HelloWorld

Once you have followed Recipe 1-5, updated the makefile to contain the contents of Listing 1-5 and generated an executable you can run GDB on your application by browsing to the folder on your command line and typing gdb HelloWorld. The new –g switch passed to Clang in the makefile from Listing 1-3 asks the compiler to generate additional information in the application that helps debuggers to provide you with accurate information about the program while it is executing in the debugger.

Image Note You may be presented with a notice informing you that your program is already up to date if you had built previously. Simply delete the existing executable file if this occurs.

Running GDB in HelloWorld should result in your command line running GDB and providing output such as that shown in Figure 1-9.

9781484201589_Fig01-09.jpg

Figure 1-9. A Running Instance of GDB

You now have a running debugger that you can use to inspect the running program while it is executing. The program has not yet begun when GDB first starts, this allows you to configure some breakpoints before you get started. To set a breakpoint you can use the break command or the b shorthand for the same command. Type break main into the GDB command prompt and hit enter. This should result in GDB echoing the command back to you along with the address of the program where the breakpoint was set and the filename and line number it detected for the function supplied. You can now type run into your window to execute the program and have GDB halt at your breakpoint. The output should resemble that shown in Figure 1-10.

9781484201589_Fig01-10.jpg

Figure 1-10. The Output as Seen When GDB Halts at the Breakpoint Set in main

At this point you have several options that allow you to continue the execution of your program. You can see a list of the most common commands below.

· step

The step command is used to step into a function that is to be called at the current line.

· next

The next command is used to step over the current line and stop on the next line of the same function.

· finish

The finish command is used to execute all of the code remaining in the current function and stop on the next line in the function that called the current function.

· print <name>

The print command followed by the name of a variable can be used to print the value of a variable in your program.

· break

The break command can be used with a line number, a function name or a source file and line number to set a breakpoint in your programs source code.

· continue

The continue command is used to resume code execution after it has been halted at a breakpoint.

· until

The until command can continue execution from a loop and stop on the first line immediately after the loop execution has finished.

· info

The info command can be used with either the locals command or the stack command to show information about the current local variables or stack state in the program.

· help

You can type help followed by any command to have GDB give you information about all of the different ways that a given command can be used.

The GDB debugger can also be run with the command –tui. This will give you a view of the source file you are currently debugging at the top of the window. You can see how this looks in Figure 1-11.

9781484201589_Fig01-11.jpg

Figure 1-11. GDB with a Source Window

Recipe 1-7. Debugging Your C++ Programs on OS X

Problem

The OS X operating system does not provide any easy method for installing and using GDB.

Solution

Xcode comes with the LLDB debugger than can be used on the command line in-place of GDB.

How It Works

The LLDB debugger is, in essence, very similar to the GDB debugger used in Recipe 1-6. Changing between GDB and LLDB is simply a case of learning how to carry out the same simple tasks in both by using the commands provided by each to carry out the same task.

You can execute LLDB on your HelloWorld executable by browsing to the directory containing HelloWorld in Terminal and typing lldb HelloWorld. This will give you output that resembles that of Figure 1-12.

9781484201589_Fig01-12.jpg

Figure 1-12. The LLDB Debugger Running in an OS X Terminal

Image Note You will need to compile your program using the –g switch. Take a look at Listing 1-3 to see where this goes if you are unsure.

Once you have LLDB running as shown in Listing 1-12 you can set a breakpoint on the first line of main by typing breakpoint set –f HelloWorld.cpp –l 8, or b main as shorthand. You can use the run command to begin execution and have it halt at the breakpoint that you’ve just set. When the program stops you can use the next command to step over the current line and halt on the next line. You could have used the step command to step into a function on the current line and halt on the first line of the function. The finish command will step out of the current function.

You can quit LLDB by typing q and hitting enter. Restart LLDB and type breakpoint set –f HelloWorld.cpp –l 9. Follow this with the run command and LLDB should print the source around the line where the application has stopped. You can now type print output to see the value stored by the output variable. You can also use the frame variable command to see all of the local variables in the current stack frame.

These simple commands will allow you to use the LLDB debugger adequately enough while working through the samples provided along with this book. The following list can be used as a handy cheat sheet while working with LLDB.

· step

The step command is used to step into a function that is to be called at the current line.

· next

The next command is used to step over the current line and stop on the next line of the same function.

· finish

The finish command is used to execute all of the code remaining in the current function and stop on the next line in the function that called the current function.

· print <name>

The print command followed by the name of a variable can be used to print the value of a variable in your program.

· breakpoint set –-name <name>

· breakpoint set –file <name> --line <number>

The breakpoint command can be used with a line number, a function name or a source file and line number to set a breakpoint in your programs source code.

· help

You can type help followed by any command to have GDB give you information about all of the different ways that a given command can be used.

Recipe 1-8. Switching C++ Compilation Modes

Problem

You would like to be able to switch between the different C++ standards before compiling your programs.

Solution

The std switch is supplied by Clang so that you can specify the C++ standard to be used when compiling.

How It Works

Clang builds with the C++98 standard by default. You can use the std argument with Clang++ to tell the compiler to use a standard other than the default. Listing 1-4 shows a makefile that is configured to build a program using the C++14 standard.

Listing 1-4. Building with C++14

HelloWorld: HelloWorld.cpp
clang++ -std=c++1y HelloWorld.cpp -o HelloWorld

The makefile in Listing 1-4 shows how you can specify that Clang should build your source file using C++14. This example was written using Clang 3.5 that uses the c++1y command to represent C++14.

Listing 1-5 shows how you can build a program using C++11.

Listing 1-5. Building with C++11

HelloWorld: HelloWorld.cpp
clang++ -std=c++11 HelloWorld.cpp -o HelloWorld

In Listing 1-5 you want to use the c++11 option with the std switch to build with C++11. Finally, Listing 1-6 shows how to configure Clang to explicitly build with C++98.

Listing 1-6. Building with C++98

HelloWorld: HelloWorld.cpp
clang++ -std=c++98 HelloWorld.cpp -o HelloWorld

The makefile in Listing 1-6 can be used to explicitly build with C++98. You can achieve the same result by leaving out the std command altogether and Clang will build using C++98 by default.

Image Note It’s not guaranteed that every compiler will use C++98 by default. Check with your compiler’s documentation if you’re unsure which standard is the default. You can also be adventurous with Clang and enable its experimental C++17 support using the c++1z option!

Recipe 1-9. Building with the Boost Library

Problem

You would like to write a program using the Boost library.

Solution

Boost is supplied as source code that can be included with and compiled into your application.

How It Works

Boost is a large C++ library that includes all sorts of great functionality. Coverage of the entire library is out of the scope of this book; however the string formatting library will be used. You can acquire the Boost library from the Boost website at http://www.boost.org/.

You will be able to get a compressed folder from the Boost website that contains the latest version of the Boost library. The only folder you absolutely need to be able to include basic boost functionality is the boost folder itself. I have downloaded Boost 1.55 and therefore I have created a folder inside my project folder named boost_1_55_0 and copied the boost folder into this location from the downloaded version.

Once you have a project folder set up with a downloaded copy of Boost you can include Boost header files into your source code. Listing 1-7 shows a program that uses the boost::format function.

Listing 1-7. Using boost::format

#include <iostream>
#include "boost/format.hpp"

using namespace std;

int main()
{
std::cout << "Enter your first name: " << std::endl;
std::string firstName;
std::cin >> firstName;

std::cout << "Enter your surname: " << std::endl;
std::string surname;
std::cin >> surname;

auto formattedName = str( boost::format("%1% %2%"s) % firstName % surname );
std::cout << "You said your name is: " << formattedName << std::endl;

return 0;
}

The code in Listing 1-7 shows how you can include a Boost header into a source file and how that file’s functions can be used in your program.

Image Note Don’t worry about how the format function works if it’s not immediately clear, it is covered in Chapter 3.

You must also tell the compiler where to look for the Boost header files in a makefile otherwise your program will not compile. Listing 1-8 shows the contents of the makefile that can be used to build this program.

Listing 1-8. A makefile to Build with Boost

main: main.cpp
clang++ -g -std=c++1y -Iboost_1_55_0 main.cpp -o main

The makefile in Listing 1-8 passes the –I option to Clang++. This option is used to tell Clang that you would like to include the given folder in the search paths used when including files using the #include directive. As you can see I have passed the boost_1_55_0 folder that I created in my project folder. This folder contains the boost folder that you can see used when including a Boost header in Listing 1-7.

Image Note If you’re having trouble getting this example to work and aren’t sure of where to put the Boost header files you can download the samples that accompany this book from the www.apress.com/9781484201589.