These are globally cached variables that you are trying to rewrite in your first approach.
Changing these compiler / linker parameters locally requires specific target configuration properties or generator expressions . So, take the second approach and How to set specific compiler flags for a specific purpose in a specific build configuration using CMake? I would get:
target_compile_options( MyLib PRIVATE "/W3 /nologo /EHsc" "$<$<CONFIG:Debug>:/MTd /Od /Ob0 /Zi /RTC1 /DDEBUG /D_DEBUG>" "$<$<CONFIG:Release>:/MT /O2 /Ob2 /DNDEBUG>" )
or for versions of CMake <= 2.8.12 (see also policy CMP0043 ):
set_target_properties( MyLib PROPERTIES COMPILE_FLAGS "/W4 /nologo /EHsc" COMPILE_FLAGS_DEBUG "/MTd /Od /Ob0 /Zi /RTC1" COMPILE_FLAGS_RELEASE "/MT /O2 /Ob2" COMPILE_DEFINITIONS_DEBUG "DEBUG;_DEBUG" COMPILE_DEFINITIONS_RELEASE "NDEBUG" )
I personally like the "OLD" way to do it better, because it replaces the default settings in the properties of a Visual Studio project. Everything passed through target_compile_options() will end in Configuration Properties / C/C++ / Command Line / Additional Options .
Some background information on why your first approach didn't work:
The CMake generator accepts everything that is set for CMAKE_<LANG>_FLAGS at the end of any CMakeLists.txt file and applies it to all libraries and executable targets in the same CMakeLists.txt file as the default compiler options when creating the build environment.
If you set the linker variables for basic CMakeLists.txt purposes in the CMakeLists.txt subdirectories, this will not help (wrong area). If I take your above code in the main CMakeLists.txt , it will work, and I will receive the following warnings (because you used the compiler options for the linker):
1>LINK : warning LNK4044: unrecognized option '/W3'; ignored 1>LINK : warning LNK4044: unrecognized option '/EHsc'; ignored 1>LINK : warning LNK4044: unrecognized option '/MTd'; ignored 1>LINK : warning LNK4044: unrecognized option '/Od'; ignored 1>LINK : warning LNK4044: unrecognized option '/Ob0'; ignored 1>LINK : warning LNK4044: unrecognized option '/Zi'; ignored 1>LINK : warning LNK4044: unrecognized option '/RTC1'; ignored 1>LINK : warning LNK4044: unrecognized option '/DDEBUG'; ignored 1>LINK : warning LNK4044: unrecognized option '/D_DEBUG'; ignored
Now I hide the cached variables of the same name set by CMake during compiler detection. For more details see:
- What is CMake syntax for setting and using variables?
- CMake: in what order are the files processed (Cache, Toolchain, ...)?
Florian Jul 25 '15 at 8:25 2015-07-25 08:25
source share