How to install gtest
How to install gtest
Install Google Test Framework Google Test on Ubuntu 20.04
Recently I’ve updated Ubuntu to version 20.04. After that I’d noticed there was an issue when installing Google Test framework gtest. I’ve found the top BING/GOOGLE search result about this subject was pointing to this blog: https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/
However, we need to do a little change in the last step. Here’s the step by step installing Google Test Framework:
sudo apt-get install libgtest-dev
sudo cmake CMakeLists.txt
If you followed Erik’s link, you would get error here:
So the correct command should be:
Please be noted I’ve copied the two files to /usr/local/lib instead of /usr/lib. It’s up to you but prefer to copying them to local lib folder.
I will create another blog about using Google gtest.
How to install gtest
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.
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.
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:
The last of the above methods is implemented with a small piece of CMake code that downloads and pulls the GoogleTest code into the main build.
Just add to your CMakeLists.txt :
Note that this approach requires CMake 3.14 or later due to its use of the FetchContent_MakeAvailable() command.
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.
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 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
How to set up googleTest as a shared library on Linux
Debian does not provide any precompiled packages for gTest anymore. They suggest you integrate the framework into your project’s makefile. But I want to keep my makefile clean. How do I set up gTest like the former versions ( Follow
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Before you start make sure your have read and understood this note from Google! This tutorial makes using gtest easy, but may introduce nasty bugs.
1. Get the googletest framework
Or get it by hand. I won’t maintain this little How-to, so if you stumbled upon it and the links are outdated, feel free to edit it.
2. Unpack and build google test
3. «Install» the headers and libs on your system.
This step might differ from distro to distro, so make sure you copy the headers and libs in the correct directory. I accomplished this by checking where Debians former gtest libs were located. But I’m sure there are better ways to do this.
4. Update the cache of the linker
. and check if the GNU Linker knows the libs
If the output looks like this:
then everything is fine.
From here on you might want to go to Googles documentation, and the old docs about the framework to learn how it works. Happy coding!
Let me answer this specifically for ubuntu users. First start by installing the gtest development package.
Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:
Now to compile your programs that uses gtest, you have to link it with:
This worked perfectly for me on Ubuntu 14.04LTS.
It took me a while to figure out this because the normal «make install» has been removed and I don’t use cmake. Here is my experience to share. At work, I don’t have root access on Linux, so I installed the Google test framework under my home directory:
To install the package in
/usr/gtest/ as shared libraries, together with sample build as well:
To validate the installation, use the following test.c as a simple test example:
If you happen to be using CMake, you can use ExternalProject_Add as described here.
This avoids you having to keep gtest source code in your repository, or installing it anywhere. It is downloaded and built in your build tree automatically.
Update for Debian/Ubuntu
So, to get your libraries from the package repository, you can do the following:
If you want the most current version of Google Test, download it from github. After that, the steps are similar:
As you can see, the path where the libraries are created has changed. Keep in mind that the new path might be valid for the package repositories soon, too.
Getting started with Google Test (GTest) on Ubuntu
by Erik Smistad · Published July 5, 2012 · Updated July 5, 2012
Google test is a framework for writing C++ unit tests. In this short post, I explain how to set it up in Ubuntu.
Start by installing the gtest development package:
sudo apt-get install libgtest-dev
Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:
sudo apt-get install cmake # install cmake cd /usr/src/gtest sudo cmake CMakeLists.txt sudo make # copy or symlink libgtest.a and libgtest_main.a to your /usr/lib folder sudo cp *.a /usr/lib
Lets say we now want to test the following simple squareRoot function:
In the following code, we create two tests that test the function using a simple assertion. There exists many other assertion macros in the framework (see http://code.google.com/p/googletest/wiki/Primer#Assertions). The code contains a small main function that will run all of the tests automatically. Nice and simple!
The next step is to compile the code. I’ve set up a small CMakeLists.txt file below to compile the tests. This file locates the google test library and links it with the test application. Note that we also have to link to the pthread library or the application won’t compile.
Compile and run the tests:
Have fun testing! You can download all of the code above at my Github page: https://github.com/smistad/GTest
References
Memory-mapped files using the boost library
October 11, 2012
by Erik Smistad · Published October 11, 2012
AMD OpenCL-OpenGL interoperability on Ubuntu Linux
by Erik Smistad · Published June 2, 2019
OpenCL-OpenGL interoperability problems on AMD GPUs and Linux
by Erik Smistad · Published August 22, 2013 · Last modified May 28, 2016
81 Responses
After adding above line, your code works like charm.
undefined reference to main…
how to write gtest in cpp if there is no return value from the function.
please show the sample for the same
Modern CMake suggests never using include_directories() as you are operating on the directory level. It’s much better operate just on the targets. See Youtube video (at:18:26) “C++Now 2017: Effective CMake” by Daniel Pfeifer
Hi, thanks for this quick guidance. However, I constantly meeting this same error:
tests.cpp:(.text+0xf8): undefined reference to `testing::Message::Message()’
anything I did wrong?
How to get html code coverage report for this tutorial…please help me
you can use “sudo make install” instead of copying the lib
How would this work on Linux Mint OS? I’ve been playing with it, and it doesn’t work the same.
Gtest is running in ubuntu 16.04 but not in ubuntu 18.04. Could you please tell what will be the issue.
[==========] Running 10 tests from 5 test cases.
[———-] Global test environment set-up.
[———-] 5 tests from AgentAppTest
[ RUN ] AgentAppTest.test_getInstance
When 1st test case encountered it will stop running.
Add gtest_main to the target_link_libraries so you can remove your main method in the test code. Like so:
Great! I didn’t know that, thanks for the tip
Very helpful guide and compensates for Google’s near universal-inability to provide decent docs or getting started guides for its open source projects. Thanks very much for this!
compilation errors have occurred while I build the FAST library on ubuntu.
/home/kerax/Desktop/FAST/src/source/CL/cl.hpp:4755:28: warning: ignoring attributes on template argument ‘cl_int
VECTOR_CLASS* binaryStatus = NULL,
^
In file included from /home/kerax/Desktop/FAST/src/source/CL/OpenCL.hpp:5:0,
from /home/kerax/Desktop/FAST/src/source/FAST/RuntimeMeasurementManager.hpp:6,
from /home/kerax/Desktop/FAST/src/source/FAST/ExecutionDevice.hpp:5,
from /home/kerax/Desktop/FAST/src/source/FAST/Data/DataObject.hpp:6,
from /home/kerax/Desktop/FAST/src/source/FAST/AffineTransformation.hpp:4,
from /home/kerax/Desktop/FAST/src/source/FAST/Visualization/View.hpp:5,
from /home/kerax/Desktop/FAST/src/source/FAST/Visualization/WindowWidget.hpp:13,
from /home/kerax/Desktop/FAST/src/source/FAST/Visualization/WindowWidget.cpp:1:
/home/kerax/Desktop/FAST/src/source/CL/cl.hpp:4755:28: warning: ignoring attributes on template argument ‘cl_int
VECTOR_CLASS* binaryStatus = NULL,
^
CMakeFiles/Makefile2:187: recipe for target ‘CMakeFiles/FAST.dir/all’ failed
make[1]: *** [CMakeFiles/FAST.dir/all] Error 2
Makefile:129: recipe for target ‘all’ failed
make: *** [all] Error 2
I just see two warnings, the actual error must be somewhere else in the output. If you need any help compiling FAST, please use the gitter chatrom instead: https://gitter.im/smistad/FAST
Crazy. The ubuntu package is not even compiled…
How to add the gtest libraries using g++?
If you want to write your own function, do hypotenuse rather than messing with a square root function that works!
That’s really helpful, thanks!
It works perfectly on Raspberry Pi 3 as well. Thank you so much 🙂
Hello,
If I separate the main test from the code, it does not execute the tests and says 0 test executed. Any idea?.
If you want to split the tests over multiple files you need to add the files to the line add_executable(runTests tests.cpp newFile.cpp) in CMakeLists.txt
very helpful, thanks
Very helpful and effective. Thanks a lot.
Thank You. I had struggled months ago trying to get going with GoogleTest.
Your example gave me reassurance that the install went correctly.
I used it on Centos 7
# s/apt-get/yum
Again thanks for helping some many others.
Hello Erik,
I don’t find the gmock after following your setup instructions here(by installing libgtest-dev). How can I add gmock seamlessly and run successfully? I tried but I am keeping getting some error. So I have to uninstall libgtest-dev.
Thanks
Great. Thanks a lot for this helpful info!!
Thanks…It helped me a lot.
Thanks very much..
Please some one help to resolve this.
correct the spelling of SquareRoot in tests.cpp code.
Haven’t tried google mock. Personally, I have moved on to using catch testing framework instead https://github.com/philsquared/Catch
Hi,
How to create link to the pthread library on ubuntu?
Regards
If you are compiling directly with gcc you can simply add -lpthread
Thanks! Solved my problem
Great guide for beginners, thank you!
Thanks Erik, helped me get started using gTest for my project.
Really clear, simple, short guide that did exactly what I wanted. Thank you!
Hi,
thanks for this guide. It is working now.
Thank you very much, this was very helpful!
At the last step, when I type cmake CMakeLists.txt, I get these errors:
CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:91 (MESSAGE):
Could NOT find GTest (missing: GTEST_INCLUDE_DIR)
Call Stack (most recent call first):
/usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:252 (_FPHSA_FAILURE_MESSAGE)
/usr/share/cmake-2.8/Modules/FindGTest.cmake:150 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
CMakeLists.txt:4 (find_package)
— Configuring incomplete, errors occurred!
Do you know how to solve this problem? Thanks.
I have solved this problem myself.
Previously I was downloading Google test from
https://code.google.com/p/googletest/
and got the error.
Now I am doing:
sudo apt-get install libgtest-dev
and exactly follow your steps. Now things work well.
my folder structure is as below :
-rw-r–r– 1 root root 4574 Sep 19 14:48 Makefile
-rw-r–r– 1 root root 499 Sep 19 14:22 tests.cpp
-rw-r–r– 1 root root 175 Sep 18 18:33 whattotest.cpp
I got some reference error while execute “make” command.
Error :
Linking CXX executable runTests
CMakeFiles/runTests.dir/tests.cpp.o: In function `testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, int const&, double const&)’:
tests.cpp:(.text._ZN7testing8internal11CmpHelperEQIidEENS_15AssertionResultEPKcS4_RKT_RKT0_[testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, int const&, double const&)]+0x9b): undefined reference to `testing::internal::EqFailure(char const*, char const*, testing::internal::String const&, testing::internal::String const&, bool)’
CMakeFiles/runTests.dir/tests.cpp.o: In function `testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, double const&, double const&)’:
tests.cpp:(.text._ZN7testing8internal11CmpHelperEQIddEENS_15AssertionResultEPKcS4_RKT_RKT0_[testing::AssertionResult testing::internal::CmpHelperEQ(char const*, char const*, double const&, double const&)]+0x99): undefined reference to `testing::internal::EqFailure(char const*, char const*, testing::internal::String const&, testing::internal::String const&, bool)’
collect2: ld returned 1 exit status
make[2]: *** [runTests] Error 1
make[1]: *** [CMakeFiles/runTests.dir/all] Error 2
make: *** [all] Error 2
Please help me in this.
Thanks,
Deepakgiri Aparnathi
I don’t know. I haven’t seen this error before.
Google Test Compiled From Source
A step-by-step walk-through to get Google Test on your system.
In this guide I compile the Google Test from the GitHub repository on my system, in my case, an Ubuntu 20, but I have also reproduced these steps on a Mac OS. There are only some minor command argument changes and I will highlight them as we walk through this.
After compiling Google Test and installing it on the system, I will show how to use it in a simple example.
One of the choices you will need to make is whether you want to compile Google Test from master, with the latest commit, or from a version release.
If you decide to compile from master, you get the latest additions, if you compile from a version release, you get the best stability.
I have compiled both from master and from version release and both choices worked just fine for me.
Compile
First, create a working directory and clone the repository.
If you want to compile from a version release, you can list tags and select a version accordingly, usually the latest version is the right choice.
If you decide to compile from master then, have a look at the GitHub project and make sure the latest version passes.
At this point all steps are the same. Create a build directory within the repository and compile
Note: First, let me show you what I do with my Ubuntu. After, what I did on Mac OS.
On Mac OS, I had to explicitly set the C++ standard version 17.
At this point, you only need to install the library. With that said, I don’t like to install files without a proper packaging system, so I usually create a simple DEB package and install, upgrade and remove as I need. Unfortunately, I cannot tell you how to create a package on Mac OS, because I haven’t done that yet. What comes next is only for Debian-like systems. At the end, I show a workaround for Mac OS.
Create a file named “control” within the DEBIAN directory:
With the following content:
Next, create the DEB package:
Finally, install the package:
At this point, you don’t need the compiled files. So, feel free to delete them.
Now, on Ubuntu, you have the header files at “/usr/local/include/gtest” and “/usr/local/include/gmock”. You can find the libraries at “/usr/local/lib”:
On Mac OS, you can run the same “DESTDIR” command I showed above and leave the files there.
Example
Create a file “example.cpp”:
To compile this on Ubuntu, you don’t need to specify the location of the headers or libraries, because they have been installed on a default path. So, this suffices:
On Mac OS, there are three small changes. First, pthread are not available, next the header and library files are not in a standard location, so you need to tell the compiler and linker where they are and finally, use the c++17 standard version.
Finally, run the program:
One more thing, if you want to use “gmock”, don’t forget to include the headers in your code:
Источники информации:
- http://github.com/google/googletest/blob/main/googletest/README.md
- http://stackoverflow.com/questions/13513905/how-to-set-up-googletest-as-a-shared-library-on-linux
- http://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/
- http://medium.com/@jgrant.esteve/google-test-compiled-from-source-c7ab87329321