Set Definitions for external sub directory

I am adding google test to my project as a sub directory. Is there a better way to add defines to just that subdirectory rather than…

add_definitions(-DGTEST_HAS_PTHREAD=0)
add_subdirectory(googletest)
remove_definitions(-DGTEST_HAS_PTHREAD=0)

You may be able to do:

add_subdirectory(googletest)
set_property(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/googletest" APPEND
  PROPERTY COMPILE_DEFINITIONS "-DGTEST_HAS_PTHREAD=0")

I don’t know if you’d need to add it to every subdirectory manually as well (you should only need it for the source directory where add_library is performed). If so, your example code may be the most convenient way.

Unfortunately, that didn’t seem to work. The googletest directory is external to our source directory if that makes a difference too. I did change the DIRECTORY argument to point to that directory, but it made no difference.

Then what you have is probably the only way to do it.

Actually, maybe you can target_compile_definitions(googletest PRIVATE GTEST_HAS_PTHREAD=0) after the add_subdirectory.

https://github.com/google/googletest/blob/0eea2e9fc63461761dea5f2f517bd6af2ca024fa/googletest/CMakeLists.txt#L22 reads:

option(gtest_disable_pthreads "Disable uses of pthreads in gtest." OFF)

So you can either pass -Dgtest_disable_pthreads=ON when configuring, or you can write:

set(gtest_disable_pthreads ON)
add_subdirectory(googletest)

That code example will only work reliably with CMake 3.13 or later, as it is currently written. In earlier CMake versions, the option() command won’t consider non-cache variables for the initial value of gtest_disable_pthreads where the cache variable does not exist yet. If there is no cache variable by that name, the option command will use its own default and will ignore any non-cache gtest_disable_pthreads variable when doing so. For subsequent runs, the cache variable will exist and then the non-cache variable will override the cache variable. It’s messy, which is why the CMake 3.13 behavior is more intuitive (option() uses non-cache variable if it exists and doesn’t even create a cache variable). If relying on CMake 3.13 behavior, the project should ensure it sets its minimum CMake version requirement accordingly (i.e. cmake_minimum_required(VERSION 3.13) or similar).

1 Like

Thank you all for the input! The option route does work. It’s just that there are more defines outside of just that option that need to be set. @ben.boeckel solutions of using target_compile_definitions after the add_subdirectory worked.