- Raymii.org
- C++ project setup with CMake & unit tests (google test)
- Table of Contents
- Install cmake & googletest
- Folder structure
- CMakeLists.txt
- Main folder CMakeLists.txt
- src folder CMakeLists.txt:
- tst folder CMakeLists.txt:
- Add some (example) source code and tests
- Source Code
- Test code
- Compile all the things
- Run all the things
- Adding Googletest To Existing CMake Project
- Google test cmake windows
Raymii.org
C++ project setup with CMake & unit tests (google test)
Published: 01-10-2019 | Last update: 06-11-2019 | Author: Remy van Elst | Text only version of this article
❗ This post is over one year old. It may no longer be up to date. Opinions may have changed.
Table of Contents
This guide will show you how to setup a new C++ project with CMake and unit tests via Google’s test framework. With this setup you can get started right away with test-driven-development in C++. It is also simple enough to look and figure out how to add gtest to your existing project and start doing TDD on your legacy (existing) codebase.
The picture below shows the end result, a running unit test:
There are a million different ways to «do» C++ projects, but using CMake and the google testing framework has my preference. That’s not to say that using a Makefile or Boost Unit Test is bad, use whatever suits your needs. This guide however will focus on just CMake and gtest .
It assumes a system running Ubuntu (18.04). It also works on Windows with mingw , but I haven’t tested in with MSVC.
My preferred code editor is CLion from Jetbrains, which has most of this built in. This guide however focusses on the manual / command line way since CLion is nonfree (and paid) software.
The process is not that complicated:
- Install software (cmake and googletest)
- Create folder structure
- Create the CMakeLists.txt files
- Create some sample code and sample tests
- Compile everything
- Run the tests
Install cmake & googletest
I assume you already have your compiler installed and working. Installing cmake can be done with the package manager on Ubuntu:
On Windows, you can use MinGW or cygwin to install your development tools including CMake. Clion offers a nice GUI for that.
Googletest is available as a git repository which you can clone and then copy into your project. You could go all fancy with CMake scripts to download it if it’s not already in your project, but since you can clone once and copy later on I choose not to automate it. Clone the repository:
gtest comes with a CMakeLists.txt so integrating it in your project is easy.
Folder structure
Create your C++ project folder. I like to keep the following structure for simple projects:
Here is a oneliner to create the folders:
Copy the googletest repository folder your cloned earlier into the lib/ folder.
If you have multiple components you can create extra sub folders, but that does require tweaking the CMakeLists.txt files to work with multiple libraries.
Most of my personal projects are simple enough to fit into one folder as above.
In the tst folder the unit tests reside. I try to keep the tests limited to the same function in seperate files. In the above example I have Formula.h and Formula.cpp , which house the example Formula class. All unit tests related to this class thus should reside in Formula-test.cpp .
CMakeLists.txt
The file CMakeLists.txt contains a set of directives and instructions describing the project’s source files and targets (executable, library, or both). This can get quite complex quite fast, CMake has many options. I try to keep it simple in this guide.
I’m using a non-recommended way to include files. For simple projects with a few files you should use the following:
That is a recursive search to include all *.cpp and *.h in the folder. In my IDE I have auto-reload enabled, that way I can’t forget to add a file to CMakeLists.txt every time. For proper administration you should not use this since it just includes everything, could have unwanted side-effects.
Update 2019-11-07: If you want Boost in this setup, read this article from me.
Each subdirectory in our case also needs a CMakeLists.txt file.
Main folder CMakeLists.txt
The name of the project is ExampleProject , that variable is used in other files. The rest of the file just includes the different subfolders. If you omit the include_directories(src) , your tests will not be able to find the header files.
src folder CMakeLists.txt:
The name of the compiled program will be ExampleProject_run , which is what we defined in add_executable . The add_library is used to include the code in the unit tests.
tst folder CMakeLists.txt:
This list used the src defined library and adds the tests as a target. The compiled executable file is named ExampleProject_tst .
Add some (example) source code and tests
At this point you start developing. But since this is a example setup, I’ll add a simple class file to show you how to do the unit tests.
Source Code
Copy the below code into your project:
This function returns the given int multiplied by 2.
Test code
The following code is to setup the unit tests.
This file will run all the tests and since we recursively included everything with CMake, it will effectively run all tests in all files in this folder.
The Google Test Primer is a great starting point to learn more on the specifics of the testing framework.
Compile all the things
Now that we have sourcecode and testcode in place we can compile everything (both the binary and the tests).
Do note that you should do this in the build folder. If you do it in the main folder it will work, but it will litter up the directory.
There are now a bunch of files and folders in the build folder, most important, the Makefile . You can now compile the project:
You now have two executable files, as defined in the CMakeLists.txt :
Run all the things
If all went well, the code should run:
The tests as well:
A quick one-liner to compile and run the tests. You can run this whenever you want to re-run the tests (after changing code for example):
As you can see I changed a unit test so that it failed.
Adding Googletest To Existing CMake Project
I’m having trouble integrating googletest into my existing project. I put together a simple project to represent my project’s structure:
Project Structure
CMakeLists.txt:
existing_source/CMakeLists.txt:
new_test_source/CMakeLists.txt:
existing_source/existing.h
existing_source/main.cpp
new_test_source/main_test.cpp
Goal:
Building with CMake will create two executables, one, TestTester, and another called Test_TestTester (sorry for the odd name, it looks like I could have chosen a better project name!).
TestTester will be the main project executable which will run the code from existing_course/main.cpp and output sample() output = 1 .
Test_TestTester should be the unit tests from main_test.cpp which tests that 1 == 1 and 1 == sample() . This should run when the project is built.
Attempts:
I’ve tried using CMake’s add_subdirectory() to expose a second CMakeLists.txt in the test subdirectory which has its own add_executable() with the name of the test program, however I cannot find any output related to the test program. Using enable_testing() followed by add_test() is also failing to produce any changes.
Update:
I realized some problems and assumptions were wrong.
- Within CLion, it defaults to building a particular target. Build all ( cmake —build . —target all ) must be invoked to build the other executables.
- The other questions I read related to this don’t seem to be using the pre-compiled library. I compiled and installed googletest on my machine prior to its inclusion into the project.
- This may not be a problem, but it looks like most people choose to structure their projects with each directory having its own CMakeLists.txt file. I reorganized mine to match to make following others’ advice easier.
I updated the CMakeLists files with my changes. Using —target all builds everything appropriately, but I still can’t get the tests to run when the project is built.
Google test cmake windows
Generic Build Instructions
To build GoogleTest and your tests that use it, you need to tell your build system where to find its headers and source files. The exact way to do it depends on which build system you use, and is usually straightforward.
Build with CMake
GoogleTest comes with a CMake build script (CMakeLists.txt) that can be used on a wide range of platforms («C» stands for cross-platform.). If you don’t have CMake installed already, you can download it for free from http://www.cmake.org/.
CMake works by generating native makefiles or build projects that can be used in the compiler environment of your choice. You can either build GoogleTest as a standalone project or it can be incorporated into an existing CMake build for another project.
Standalone CMake Project
When building GoogleTest as a standalone project, the typical workflow starts with
The above command also includes GoogleMock by default. And so, if you want to build only GoogleTest, you should replace the last command with
If you are on a *nix system, you should now see a Makefile in the current directory. Just type make to build GoogleTest. And then you can simply install GoogleTest if you are a system administrator.
If you use Windows and have Visual Studio installed, a gtest.sln file and several .vcproj files will be created. You can then build them using Visual Studio.
On Mac OS X with Xcode installed, a .xcodeproj file will be generated.
Incorporating Into An Existing CMake Project
If you want to use GoogleTest in a project which already uses CMake, the easiest way is to get installed libraries and headers.
- Import GoogleTest by using find_package (or pkg_check_modules ). For example, if find_package(GTest CONFIG REQUIRED) succeeds, you can use the libraries as GTest::gtest , GTest::gmock .
And a more robust and flexible approach is to build GoogleTest as part of that project directly. This is done by making the GoogleTest source code available to the main build and adding it using CMake’s add_subdirectory() command. This has the significant advantage that the same compiler and linker settings are used between GoogleTest and the rest of your project, so issues associated with using incompatible libraries (eg debug/release), etc. are avoided. This is particularly useful on Windows. Making GoogleTest’s source code available to the main build can be done a few different ways:
- Download the GoogleTest source code manually and place it at a known location. This is the least flexible approach and can make it more difficult to use with continuous integration systems, etc.
- Embed the GoogleTest source code as a direct copy in the main project’s source tree. This is often the simplest approach, but is also the hardest to keep up to date. Some organizations may not permit this method.
- Add GoogleTest as a git submodule or equivalent. This may not always be possible or appropriate. Git submodules, for example, have their own set of advantages and drawbacks.
- Use CMake to download GoogleTest as part of the build’s configure step. This is just a little more complex, but doesn’t have the limitations of the other methods.
The last of the above methods is implemented with a small piece of CMake code in a separate file (e.g. CMakeLists.txt.in ) which is copied to the build area and then invoked as a sub-build during the CMake stage. That directory is then pulled into the main build with add_subdirectory() . For example:
New file CMakeLists.txt.in :
Existing build’s CMakeLists.txt :
Note that this approach requires CMake 2.8.2 or later due to its use of the ExternalProject_Add() command. The above technique is discussed in more detail in this separate article which also contains a link to a fully generalized implementation of the technique.
Visual Studio Dynamic vs Static Runtimes
By default, new Visual Studio projects link the C runtimes dynamically but GoogleTest links them statically. This will generate an error that looks something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch detected for ‘RuntimeLibrary’: value ‘MTd_StaticDebug’ doesn’t match value ‘MDd_DynamicDebug’ in main.obj
GoogleTest already has a CMake option for this: gtest_force_shared_crt
Enabling this option will make gtest link the runtimes dynamically too, and match the project in which it is included.
C++ Standard Version
An environment that supports C++11 is required in order to successfully build GoogleTest. One way to ensure this is to specify the standard in the top-level project, for example by using the set(CMAKE_CXX_STANDARD 11) command. If this is not feasible, for example in a C project using GoogleTest for validation, then it can be specified by adding it to the options for cmake via the DCMAKE_CXX_FLAGS option.
GoogleTest can be used in diverse environments. The default configuration may not work (or may not work well) out of the box in some environments. However, you can easily tweak GoogleTest by defining control macros on the compiler command line. Generally, these macros are named like GTEST_XYZ and you define them to either 1 or 0 to enable or disable a certain feature.
We list the most frequently used macros below. For a complete list, see file include/gtest/internal/gtest-port.h.
GoogleTest is thread-safe where the pthread library is available. After #include «gtest/gtest.h» , you can check the GTEST_IS_THREADSAFE macro to see whether this is the case (yes if the macro is #defined to 1, no if it’s undefined.).
If GoogleTest doesn’t correctly detect whether pthread is available in your environment, you can force it with
When GoogleTest uses pthread, you may need to add flags to your compiler and/or linker to select the pthread library, or you’ll get link errors. If you use the CMake script, this is taken care of for you. If you use your own build script, you’ll need to read your compiler and linker’s manual to figure out what flags to add.
As a Shared Library (DLL)
GoogleTest is compact, so most users can build and link it as a static library for the simplicity. You can choose to use GoogleTest as a shared library (known as a DLL on Windows) if you prefer.
To compile gtest as a shared library, add
to the compiler flags. You’ll also need to tell the linker to produce a shared library instead — consult your linker’s manual for how to do it.
To compile your tests that use the gtest shared library, add
to the compiler flags.
Note: while the above steps aren’t technically necessary today when using some compilers (e.g. GCC), they may become necessary in the future, if we decide to improve the speed of loading the library (see http://gcc.gnu.org/wiki/Visibility for details). Therefore you are recommended to always add the above flags when using GoogleTest as a shared library. Otherwise a future release of GoogleTest may break your build script.
Avoiding Macro Name Clashes
In C++, macros don’t obey namespaces. Therefore two libraries that both define a macro of the same name will clash if you #include both definitions. In case a GoogleTest macro clashes with another library, you can force GoogleTest to rename its macro to avoid the conflict.
Specifically, if both GoogleTest and some other code define macro FOO, you can add
to the compiler flags to tell GoogleTest to change the macro’s name from FOO to GTEST_FOO . Currently FOO can be FAIL , SUCCEED , or TEST . For example, with -DGTEST_DONT_DEFINE_TEST=1 , you’ll need to write