[CMake] modifying cmake_build_type cflags per target

Craig Scott craig.scott at crascit.com
Tue Nov 19 16:51:53 EST 2019


On Tue, Nov 19, 2019 at 10:36 PM Eric Doenges <doenges at mvtec.com> wrote:

> Am 19.11.19 um 12:09 schrieb Stéphane Ancelot:
>
> Hi,
>
> I have a particular target (using swig / jni) that must not have -O3
> -NDEBUG flags from Relase build type
>
> How can I overload this target flags ?
>
> Since CMAKE_<lang>_FLAGS_RELEASE does not map to a user-visible target
> property, you cannot override it directly (anything added to the
> COMPILE_FLAGS property is appended to the command line and does not replace
> any of the compiler flags CMake sets by itself). However, you can redefine
> this variable before you create your special target(s), and then restore it
> so that other targets are not affected:
>
> set(_CMAKE_CXX_FLAGS_RELEASE_SAVE ${CMAKE_CXX_FLAGS_RELEASE})
> set(CMAKE_CXX_FLAGS_RELEASE)
> < add your target(s) here >
> set(CMAKE_CXX_FLAGS_RELEASE ${_CMAKE_CXX_FLAGS_RELEASE_SAVE})
>
> This assumes your target is C++; if it is C, simply replace the _CXX_ with
> _C_.
>

Actually, no, that's not how it works. This is actually a great example of
why projects shouldn't generally try to avoid manipulating CMAKE_CXX_FLAGS
and should instead prefer to modify target or directory properties instead
(not possible here for the original problem, but worth highlighting
nonetheless). The (often surprising) behavior at play in the proposed
example above is that it is not the value of the CMAKE_CXX_FLAGS_RELEASE
variable at the time the target is created that matters, it's the
variable's value *at the end of the directory scope*. You can change the
variable's value as much as you like along the way before or after creating
targets, but only the final value at the end of the scope will actually be
used in the build command lines for targets created in that directory
scope. This is rarely what developers expect, but that's how it works, for
better or worse. When you start adding in calls to add_subdirectory(), it
can get really confusing what value is getting used where, so take great
care if your project really must modify these variables.

-- 
Craig Scott
Melbourne, Australia
https://crascit.com

Get the hand-book for every CMake user: Professional CMake: A Practical
Guide <https://crascit.com/professional-cmake/>
Consulting services (CMake, C++, build/release processes):
https://crascit.com/services
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://cmake.org/pipermail/cmake/attachments/20191120/2db72a8b/attachment.html>


More information about the CMake mailing list