c++cmakecpputest

How to add compile options to a CMake FetchContent-dependency?


I have a C/C++ project in which I want to use CppUTest. So I include the dependency of CppUTest with:

include(FetchContent)
FetchContent_Declare(
        CppUTest
        GIT_REPOSITORY      https://github.com/cpputest/cpputest.git
        GIT_TAG             latest-passing-build
        CONFIGURE_COMMAND   ""
        BUILD_COMMAND       ""
)
set(TESTS OFF CACHE BOOL "Switch off CppUTest Test build")
FetchContent_MakeAvailable(CppUTest)

This works fine.

In my (automotive) project, I use the C++20 standard and I need to enable all/most warnings. But when I do, CppUTest brings me a lot of warnings. So, I would like to compile CppUTest with different compiler options than the project's code.

How can I configure that in CMake? I googled a lot but didn't find anything that works.

Thanks, Stefan

PS: My simplified CMake file is:

cmake_minimum_required(VERSION 3.5)

project(projectName LANGUAGES CXX C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
    MESSAGE("Setting Clang flags:")
    SET(COMPILE_FLAGS_WARNINGS "-Weverything")
    SET(COMPILE_FLAGS_DEBUG    "-Og")
    SET(COMPILE_FLAGS_RELEASE  "-O2")
    SET(COMPILE_FLAGS_COVERAGE "--coverage")
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
    #more options here
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
    #more options here
endif()

MESSAGE("Debug: ${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS_WARNINGS} ${COMPILE_FLAGS_DEBUG}")
MESSAGE("Release: ${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS_WARNINGS} ${COMPILE_FLAGS_RELEASE}")
MESSAGE("Coverage: ${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS_WARNINGS} ${COMPILE_FLAGS_DEBUG} ${COMPILE_FLAGS_COVERAGE}")

### Dependencies:

include(FetchContent)
FetchContent_Declare(
        CppUTest
        GIT_REPOSITORY      https://github.com/cpputest/cpputest.git
        GIT_TAG             latest-passing-build
        CONFIGURE_COMMAND   ""
        BUILD_COMMAND       ""
)    

set(TESTS OFF CACHE BOOL "Switch off CppUTest Test build")
FetchContent_MakeAvailable(CppUTest)

SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS_WARNINGS}")
set(CMAKE_CXX_FLAGS_DEBUG "${COMPILE_FLAGS_DEBUG}")
set(CMAKE_CXX_FLAGS_RELEASE "${COMPILE_FLAGS_RELEASE}")
 
enable_testing()
    
### add tests
add_subdirectory(path/to/my/tests)

Solution

  • Do not use set(CMAKE_<LANG>*. Use *target* interfaces. If you do not want all stuff to be compiled with a specific option, do not set them globally. Instead:

    set_target_properties(mytests PROPERTY
        CXX_STANDARD 11
        etc.
    )
    target_compile_options(mytests PUBLIC -option1 -option2 ...)
    

    Anyway, SET(CMAKE_<LANG>_* affect targets declared after it. So move set(CMAKE_* after FetchContent_MakeAvailable(CppUTest)