38

Does CMAKE_BUILD_TYPE=Release implicitly imply -DNDEBUG?

If not: isn't it reasonable to expect that this implication takes place?

I want to know if following CMake code is redundant in my CMakeLists.txt:

if (NOT CMAKE_BUILD_TYPE MATCHES Debug)
    add_definitions(-DNDEBUG)
endif()
usr1234567
  • 21,601
  • 16
  • 108
  • 128
patryk.beza
  • 4,876
  • 5
  • 37
  • 56
  • 2
    I checked it out and it turns out that *CMake* append `-DNDEBUG` flag, but it's still problematic because [CMake documentation](https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html) does **not** explicitly mention if `-DNDEBUG` flag is added when `CMAKE_BUILD_TYPE=Debug` option is present. I prefer to avoid writing code based on undocumented behaviour because it may change in future CMake versions (though potential consequences would be small). – patryk.beza Dec 16 '15 at 01:16
  • 3
    @iharob: Author wants to know, whether this behaviour is standard/common, and is observed on **all machines**. That's why checking that on his *current machine* is not sufficient (and author *did that*). Googling is not showing answer at least on the first page. And answer is actually not so simple as it seems to be. Intention to remove redudant code, given in the question, is perfectly OK for programming. Voted to reopen. – Tsyvarev Dec 16 '15 at 07:48
  • @Tsyvarev I see, I am deeply sorry. The utility with *undocumented* documentation is *qmake* and I didn't remember that, I will delete the comment as it's misleading. – Iharob Al Asimi Dec 16 '15 at 14:22

1 Answers1

39

Yes, it is set by CMake. Grepping through the CMake code reveals, that for a host of compilers it is set. Probably they set it only for these compilers, which accepts this flag. Here one of the lines concerning GCC:

Modules/Compiler/GNU.cmake:  set(CMAKE_${lang}_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")

But be aware that many projects overwrite release/debug flags without preserving the initial setting and also overwriting user's definitions.

usr1234567
  • 21,601
  • 16
  • 108
  • 128
  • 6
    Starting in 3.7 you can set `CMAKE__FLAGS_RELEASE_INIT` explicitly and control all the compile flags - see https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_FLAGS_INIT.html. – qneill Mar 09 '21 at 15:58