Cmake change compilation flags

cmake, configuration, flags, gcc

Solution

I found solution by myself. Where is helpful `string` function. For example, i can use variable BENCH_ARCH for change ARM arch. I wrote in toolchain file after all default C/C++ flags definition. First, add variable for caching:

...
set(BENCH_ARCH "${BENCH_ARCH}" CACHE STRING "Arch" FORCE)`
...

After that, check that variable is set and replace flags variable

if(BENCH_ARCH)
    string(REGEX REPLACE "-march=[A-Za-z_0-9/-]*" "-march=${BENCH_ARCH}"          <variable, which set flags> ${<variable, which set flags>})
endif()
...

For example:

string(REGEX REPLACE "-march=[A-Za-z_0-9/-]*" "-march=${BENCH_ARCH}" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})

Now, i can use `cmake -DBENCH_ARCH=armv5te -DCMAKE_TOOLCHAIN_FILE=<...> ...` for enabling `-march=armv5te` and use `cmake -DCMAKE_TOOLCHAIN_FILE=<...> ...` for enabling default toolchain setting. Hope this will be helpful not only for me.

Problem

I want to run automatic optimization flags benchmark for my cmake project. Project is cross-compiling, basic c/cxx flags are set in toolchain file assignable with `-DCMAKE_TOOLCHAIN_FILE=<...>`. I want to change c/cxx flags during benchmarking, but I don't want to change toolchain file on each benchmark iteration. I just want to change some flags set from toolchain to other value (for example, `-mtune=cortex-a8` to `-mtune=cortex-a9`). I think the best way is use `-DMY_TUNE_FLAG=<..>`. But how I can change previously set flag? (not append flag to c/cxx flags).

Original source