Skip to content

Instantly share code, notes, and snippets.

@dlime
Last active August 24, 2024 18:06
Show Gist options
  • Save dlime/313f74fd23e4267c4a915086b84c7d3d to your computer and use it in GitHub Desktop.
Save dlime/313f74fd23e4267c4a915086b84c7d3d to your computer and use it in GitHub Desktop.
Install Google Test and Google Mock on Ubuntu
cmake_minimum_required(VERSION 3.5)
project(example LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})
add_executable(example main.cpp)
target_link_libraries(example ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
cd ~
git clone https://github.com/google/googletest.git
cd googletest
mkdir build && cd build
cmake .. -DBUILD_SHARED_LIBS=ON -DINSTALL_GTEST=ON -DCMAKE_INSTALL_PREFIX:PATH=/usr
make -j8
sudo make install
sudo ldconfig
#include <gtest/gtest.h>
TEST(test_case, example_test)
{
EXPECT_EQ(2, 2);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@skwasniak
Copy link

Not sure why but for me it did not work with the share lib flag.

So what I did was (note the -DBUILD_SHARED_LIBS=OFF):

git clone https://github.com/google/googletest.git

cd googletest
mkdir build && cd build

cmake .. -GNinja -DBUILD_SHARED_LIBS=OFF -DINSTALL_GTEST=ON -DCMAKE_INSTALL_PREFIX:PATH=/usr
cmake --build .
sudo cmake --install .
sudo ldconfig

...furthermore my CMakeLists.txt looks a little different, as I took the one from the official CMake documentation (https://cmake.org/cmake/help/v3.6/module/FindGTest.html) :

enable_testing()
find_package(GTest REQUIRED)

add_executable(foo foo.cc)
target_link_libraries(foo GTest::GTest GTest::Main)

add_test(AllTestsInFoo foo)

@Tachi107
Copy link

Tachi107 commented May 13, 2024

Never specify -DCMAKE_INSTALL_PREFIX:PATH=/usr, unless you want to break your system, as it will inevitably lead to conflicts with files managed by the system package manager (like apt). The default CMake install prefix, /usr/local, sidesteps this issue by installing files in a separate directory hierarchy - this is still less ideal than installing libgtest-dev and libgmock-dev with apt, but won't break your system. Generally speaking, never override defaults unless you really know what you're doing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment