Book Image

Advanced C++

By : Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
5 (1)
Book Image

Advanced C++

5 (1)
By: Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price

Overview of this book

C++ is one of the most widely used programming languages and is applied in a variety of domains, right from gaming to graphical user interface (GUI) programming and even operating systems. If you're looking to expand your career opportunities, mastering the advanced features of C++ is key. The book begins with advanced C++ concepts by helping you decipher the sophisticated C++ type system and understand how various stages of compilation convert source code to object code. You'll then learn how to recognize the tools that need to be used in order to control the flow of execution, capture data, and pass data around. By creating small models, you'll even discover how to use advanced lambdas and captures and express common API design patterns in C++. As you cover later chapters, you'll explore ways to optimize your code by learning about memory alignment, cache access, and the time a program takes to run. The concluding chapter will help you to maximize performance by understanding modern CPU branch prediction and how to make your code cache-friendly. By the end of this book, you'll have developed programming skills that will set you apart from other C++ programmers.
Table of Contents (11 chapters)
7
6. Streams and I/O

Importing a CMake Project into Eclipse CDT

A Ninja build file is useful for building our project in Linux. However, a CMake project is portable and can be used with other build systems and IDEs as well. Many IDEs accept CMake as their configuration file and provide a seamless experience as you modify and build your project. In this section, we will discuss how to import a CMake project into Eclipse CDT, which is a popular cross-platform C/C++ IDE.

There are multiple ways of using Eclipse CDT with CMake. The default one that CMake provides is the one-way generation of the IDE project. Here, you create the IDE project once, and any modifications you make to your IDE project will not change back the original CMake project. This is useful if you manage your project as a CMake project and do one-time builds with Eclipse CDT. However, it's not ideal if you want to do your development in Eclipse CDT.

Another way of using CMake with Eclipse CDT is to use the custom cmake4eclipse plugin. When using this plugin, you do not abandon your CMakeLists.txt file and make a one-way switch to Eclipse CDT's own project manager. Instead, you keep managing your project through the CMakeLists.txt file, which continues to be the main configuration file of your project. Eclipse CDT actively works with your CMakeLists.txt file to build your project. You can add or remove source files and make other changes in your CMakeLists.txt, and the cmake4eclipse plugin applies those changes to the Eclipse CDT project at every build. You will have a nice IDE experience while keeping your CMake project current. The benefit of this approach is that you can always quit using Eclipse CDT and use your CMakeLists.txt file to switch to another build system (such as Ninja) later. We will use this second approach in the following exercise.

Exercise 2: Importing the CMake File into Eclipse CDT

In the last exercise, you developed a CMake project and you would like to start using Eclipse CDT IDE to edit and build that project. In this exercise, we will import our CMake project into the Eclipse CDT IDE using the cmake4eclipse plugin. Perform the following steps to complete the exercise:

  1. Open Eclipse CDT.
  2. Create a new C++ project in the location of our current project (the folder that contains the CMakeLists.txt file and the src folder). Go to File | New | Project. A New Project dialog box appears like the one in the following screenshot:
    Figure 1.8: New Project dialog box
    Figure 1.8: New Project dialog box
  3. Select the C++ Project option and click on the Next button. A C++ Project dialog box appears like the one in the following screenshot:
    Figure 1.9: C++ Project dialog box
    Figure 1.9: C++ Project dialog box
  4. Accept everything, including switching to the C/C++ perspective, and click Finish.
  5. Click on the Restore button at the top-left corner to view the newly created project:
    Figure 1.10: The Restore button
    Figure 1.10: The Restore button
  6. Click on the CxxTemplate project. Go to Project | Properties, then select Tool Chain Editor under C/C++ Build from the left pane and set Current builder to CMake Builder (portable). Then, click on the Apply and Close button:
    Figure 1.11: Project properties
    Figure 1.11: Project properties
  7. Then, choose the Project | Build All menu item to build the project:
    Figure 1.12: Building the project
    Figure 1.12: Building the project
  8. In the following Console pane, you will see the output of CMake as if you called it from the command line, followed by a call to make all that actually builds our project:
    Figure 1.13: The build output
    Figure 1.13: The build output
  9. If you did not get any errors in the previous steps, you can run the project using the menu item Run | Run. If you are given some options, choose Local C/C++ Application and CxxTemplate as the executable:
    Figure 1.14: Running a project
    Figure 1.14: Running a project
  10. When it runs, you will see the output of the program in the Console pane as follows:
Figure 1.15: Output of the project
Figure 1.15: Output of the project

You have successfully built and run a CMake project using Eclipse CDT. In the next exercise, we will introduce a frequent change to our projects by adding new source files with new classes.

Exercise 3: Adding New Source Files to CMake and Eclipse CDT

As you develop significantly bigger C++ projects, you will tend to add new source files to it as the project grows to meet the set expectations. In this exercise, we will add a new .cpp and .h file pair to our project and see how CMake and Eclipse CDT work together with these changes. We will add these files inside the project using the new class wizard, but you can also create them with any other text editor. Perform the following steps to add new source files to CMake and Eclipse CDT:

  1. First, open the project that we have been using until now. In the Project Explorer pane on the left, expand the root entry, CxxTemplate, and you will see the files and folders of our project. Right-click the src folder and select New | Class from the pop-up menu:
    Figure 1.16: Creating a new class
    Figure 1.16: Creating a new class
  2. In the dialog box that opened, type ANewClass for the class name. When you click on the Finish button, you will see the ANewClass.cpp and ANewClass.h files generated under the src folder.
  3. Now, let's write some code into the ANewClass class and access it from the CxxTemplate class that we already had. Open ANewClass.cpp and change the beginning of the file to match the following, and then save the file:

    #include "ANewClass.h"

    #include <iostream>

    void ANewClass::run() {

        std::cout << "Hello from ANewClass." << std::endl;

    }

    You will see that Eclipse warns us with a Member declaration not found message:

    Figure 1.17: Analyzer warning
    Figure 1.17: Analyzer warning

    This error is generated since we need to add this to our ANewClass.h file as well. Such warnings are made possible by analyzers in IDEs and are quite useful as they help you fix your code as you are typing, without running the compiler.

  4. Open the ANewClass.h file, add the following code, and save the file:

    public:

        void run(); // we added this line

        ANewClass();

    You should see that the error in the .cpp file went away. If it did not go away, it may be because you may have forgotten to save one of the files. You should make it a habit to press Ctrl + S to save the current file, or Shift + Ctrl + S to save all the files that you edited.

  5. Now, let's use this class from our other class, CxxTemplate.cpp. Open that file, perform the following modifications, and save the file. Here, we are first importing header files and in the constructor of CxxApplication, we are printing text to the console. Then, we are creating a new instance of ANewClass and calling its run method:

    #include "CxxTemplate.h"

    #include "ANewClass.h"

    #include <string>

    ...

    CxxApplication::CxxApplication( int argc, char *argv[] ) {

      std::cout << "Hello CMake." << std::endl;

      ::ANewClass anew;

      anew.run();

    }

    Note

    The complete code of this file can be found here: https://github.com/TrainingByPackt/Advanced-CPlusPlus/blob/master/Lesson1/Exercise03/src/CxxTemplate.cpp.

  6. Try to build the project by clicking on the Project | Build All menu options. You will get some undefined reference errors in two lines. This is because our project is built with CMake's rules and we did not let CMake know about this new file. Open the CMakeLists.txt file, make the following modification, and save the file:

    add_executable(CxxTemplate

      src/CxxTemplate.cpp  

      src/ANewClass.cpp

    )

    Try to build the project again. This time you should not see any errors.

  7. Run the project using the Run | Run menu option. You should see the following output in the terminal:
Figure 1.18: Program output
Figure 1.18: Program output

You modified a CMake project, added new files to it, and ran it fine. Note that we created the files in the src folder and let the CMakeLists.txt file know about the CPP file. If you do not use Eclipse, you can simply continue with the usual CMake build commands and your program will run successfully. So far, we have checked out the sample code from GitHub and built it both with plain CMake and with the Eclipse IDE. We also added a new class to the CMake project and rebuilt it in Eclipse IDE. Now you know how to build and modify CMake projects. In the next section, we will perform an activity of adding a new source-header file pair to the project.

Activity 1: Adding a New Source-Header File Pair to the Project

As you develop C++ projects, you add new source files to it as the project grows. You may want to add new source files for various reasons. For example, let's say you are developing an accounting application in which you calculate interest rates in many places of your project, and you want to create a function in a separate file so that you can reuse it throughout your project. To keep things simple, here we will create a simple summation function instead. In this activity, we will add a new source-header file pair to the project. Perform the following steps to complete the activity:

  1. Open the project that we created in the earlier exercise in the Eclipse IDE.
  2. Add the SumFunc.cpp and SumFunc.h file pair to the project.
  3. Create a simple function named sum that returns the sum of two integers.
  4. Call the function from the CxxTemplate class constructor.
  5. Build and run the project in Eclipse.

The expected output should be similar to the following:

Figure 1.19: Final output
Figure 1.19: Final output

Note

The solution for this activity can be found on page 620.

In the following section, we will talk about how to write unit tests for our projects. It is common to divide projects into many classes and functions that work together to achieve the desired goal. You must manage the behavior of these classes and functions with unit tests to ensure that they behave in expected ways.