Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active September 4, 2023 01:20
Show Gist options
  • Save scivision/8f035250edb2e3a648ad6ace1c9d019d to your computer and use it in GitHub Desktop.
Save scivision/8f035250edb2e3a648ad6ace1c9d019d to your computer and use it in GitHub Desktop.
Override CMake-generated compiler flags

Override CMake automatic compiler flags

CMake outputs compiler flag defaults based on project build settings, compiler, operating system, etc. These default compiler flags can be overriden by appending one's own compiler flags later in the command line. To observe this, build this example like:

cmake -Bbuild

cmake --build build -v
cmake_minimum_required(VERSION 3.10)
project(foo LANGUAGES C)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# use add_compile_options() instead of setting CMAKE_C_FLAGS to ensure the user flags come last,
# that is the user flags take precedence
add_compile_options(
"$<$<COMPILE_LANGUAGE:C>:-Ofast;-march=native;-ftree-vectorize>"
)
file(GENERATE OUTPUT main.c CONTENT "int main() { return 0; }")
add_executable(main ${CMAKE_CURRENT_BINARY_DIR}/main.c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment