Skip to content

Instantly share code, notes, and snippets.

@ptorre
Last active February 23, 2022 03:12
Show Gist options
  • Save ptorre/62acb2b9cfd3587cf262eb19b1184feb to your computer and use it in GitHub Desktop.
Save ptorre/62acb2b9cfd3587cf262eb19b1184feb to your computer and use it in GitHub Desktop.
Configuring GoogleTest in CMakeList.txt (Building internally vs. using as installed on host).
###
# Compiler flags (not required for using GoogleTest)
#
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wextra")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wextra")
##########
# Use ONE of the below sections to use GoogleTest.
# This example assumes that main_test.cc contains your tests.
##########
########## OPTION 1
# Download GoogleTest as part of the build's configure step.
# Will rebuild gtest and gmock after a clean.
#
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/refs/tags/release-1.11.0.zip
)
FetchContent_MakeAvailable(googletest)
enable_testing()
# Your cmake commands. . .
add_executable(
main_test
main_test.cc
)
target_link_libraries(
main_test
gtest_main # Or gtest
gmock
)
# Use discovery for tests for `test` target
include(GoogleTest)
gtest_discover_tests(main_test)
########## OPTION 2
# Use GoogleTest that is installed on build host.
# No need to rebuild gtest or gmock after a clean.
#
find_package (GTest CONFIG REQUIRED)
enable_testing()
# Your cmake commands. . .
add_executable(
main_test
main_test.cc
)
target_link_libraries(
main_test
GTest::gtest_main # or GTest::gtest
GTest::gmock
)
# Use discovery for tests for `test` target
include(GoogleTest)
gtest_discover_tests(main_test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment