Setting compiler flags in CMakeLists.txt

In my CMakeLists.txt I have:

SET( CMAKE_CXX_FLAGS  "-Ofast -DNDEBUG -std=c++20 -march=native -fpic -ftree-vectorize")

However I found that CMake also adds following flags:

-O3 -DNDEBUG -std=gnu++20 -arch arm64

I found this by running following command:

cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON build/Release

These flags are actually causing my program to run almost 2x slower! and took me a long time to figure it out. How can I tell CMake to use only the flags I have told it to use? Could someone please help me?

I am using

cmake --version                                                       [17:44:08]
cmake version 3.27.0-rc4

on mac os

It seems like CMake uses CMAKE_CXX_FLAGS_RELEASE and CMAKE_CXX_FLAGS_DEBUG (depending on the current value of CMAKE_BUILD_TYPE) in addition to CMAKE_CXX_FLAGS. The -O3 you see is likely set by default in CMAKE_CXX_FLAGS_RELEASE.

If you want to use only the flags you manually specified, you can set the build type-specific flags to the empty string like this:

SET( CMAKE_CXX_FLAGS_DEBUG  "")
SET( CMAKE_CXX_FLAGS_RELEASE  "")
SET( CMAKE_CXX_FLAGS  "-Ofast -DNDEBUG -std=c++20 -march=native -fpic -ftree-vectorize")

This is addressed by using “add_compile_options()”, which is generally preferred.

cmake_minimum_required(VERSION 3.10)

project(foo LANGUAGES CXX)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_compile_options(
"$<$<COMPILE_LANGUAGE:CXX>:-Ofast;-DNDEBUG;-std=c++20;-march=native;-fpic;-ftree-vectorize>"
)

file(GENERATE OUTPUT main.cpp CONTENT "int main(void) { return 0; }")

add_executable(main ${CMAKE_CURRENT_BINARY_DIR}/main.cpp)
cmake -Bbuild -DCMAKE_BUILD_TYPE=Release --fresh
  "command": "/usr/bin/cc -O3 -DNDEBUG -Ofast -DNDEBUG -std=c++20 -march=native -fpic -ftree-vectorize 

I find this puts the user flags at the end, e.g. the order is like “-O3 -Ofast” which is what you desire, to have -Ofast take precedence.

thank you.