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…


You may be able to do:


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. 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)

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.