Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "Modern CMake" to set compiler flags? [duplicate]

Tags:

c++

cmake

I am trying to learn CMake with a simple project. This is my sample CMakeLists.txt

cmake_minimum_required(VERSION 3.11 FATAL_ERROR)
set(PROJECT_NAME "MyLib" CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
project(${PROJECT_NAME})

include(${CMAKE_SOURCE_DIR}/Sources.cmake) 
set(SOURCE_FILES ${COMMON_CPP_FILES} ${COMMON_H_FILES})

include_directories(include)

add_compile_options("$<$<CONFIG:Debug>:/EHa /MTd /W3 /w14640>")

add_library(${PROJECT_NAME} STATIC ${SOURCE_FILES})

I tried to create a Visual Studio project based on this file but I cannot figure out how to properly set the compile flags. When I open Visual Studio I can see the flags (/EHa) as part of "Additional Options" but I can still see the default (/EHsc) flags.

enter image description here

Why the default flags are still there and how can I make sure the compiler is really using the flags that I have specified?

like image 459
Ali Avatar asked Oct 16 '25 18:10

Ali


1 Answers

You can check what default flags CMake uses by printing CMAKE_CXX_FLAGS and CMAKE_CXX_FLAGS_{RELEASE|DEBUG}. Setting these variables with something like

set(CMAKE_CXX_FLAGS "") 

will not clear them however.

The only way I've found to do what you are saying (clear specific default flags) is something like this for every default flag:

string(REPLACE "/EHsc" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
string(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")

Why you cannot clear all the default flags easily and without this syntax is beyond me, however.

like image 85
Ganea Dan Andrei Avatar answered Oct 19 '25 07:10

Ganea Dan Andrei