CMake pass LVVM compiler optimisation options

I can’t figure out how i can pass optimization option for the release build to the clang compiler. I want to try “-ffast-math” option. I tried to pass it as an argument but without any success so far.

Any help is welcome.

Adding something like this to your CMakeLists.txt file would likely work, though I haven’t tested:

  target_compile_options(MyTarget PUBLIC $<$<CONFIG:Release>:-ffast-math>)
1 Like

Thanks. That seems to work. I also found that this works the same way:

sudo cmake -B cmake-build -DCMAKE_PREFIX_PATH=../juce/install -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-ffast-math"

Not sure what the better option is.

To me it’s very simple:
The command line option means that each invoker needs to ‘know’ about the special build flags.

If it’s only you, and you know for sure that you’ll either remember the flags or document them somewhere where you’ll remember, it’s good. Also if you want to be able to configure the build with different flags each time, it’s probably the best way.

However, if you want to make sure that the product always built with those same flags, keeping them in the CMakeLists.txt file is better. Personally I really like to battle with build systems problems only once and then do as much as I can to forget about them later.

1 Like

Another point is that it’s generally against modern CMake practice to explicitly set CMAKE_CXX_FLAGS et al at a global scope, but instead narrow such things down to the targets that actually need them, so in my opinion the solution proposed by @McMartin is the way to go.

Setting things target based makes combining different CMake targets from different projects a lot easier and leads to more portable and self-contained CMake code, as this way the target carries the information “if I’m compiled with clang, please compile my source files with the -ffast-math option”, while at the same time another target compiled within the same project might run into trouble if compiled with the same flag and could be compiled with different options. This target-centered way of thinking and designing CMake scrips helped me a lot while learning to use CMake for some medium scale projects with quite a few CMake dependencies lately for the first time.