# Using different compiler flags when using different compilers, VS generator

**URL:** https://discourse.cmake.org/t/using-different-compiler-flags-when-using-different-compilers-vs-generator/12810
**Category:** Usage
**Created:** [October 21, 2024, 5:23pm UTC](https://discourse.cmake.org/t/using-different-compiler-flags-when-using-different-compilers-vs-generator/12810 "2024-10-21T17:23:39Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![thomashenry79](https://discourse.cmake.org/user_avatar/discourse.cmake.org/thomashenry79/32/5032_2.png) [@thomashenry79](https://discourse.cmake.org/u/thomashenry79)
#### Post date: [October 21, 2024, 5:23pm UTC](https://discourse.cmake.org/t/using-different-compiler-flags-when-using-different-compilers-vs-generator/12810/1 "2024-10-21T17:23:39Z")

</div>

Working in an MSVC/Visual Studio shop but we need to start building using multiple compilers (Clang, Intel, etc). Using the VS generator works ok, eg:

> cmake -B build-dir-intel -G “Visual Studio 17” -T “Intel C++ Compiler 2024”  
> cmake -B build-dir-clang -G “Visual Studio 17” -T “ClangCl”  
> cmake -B build-dir-143 -G “Visual Studio 17” -T “v143”  
> cmake -B build-dir-142 -G “Visual Studio 17” -T “v142”

Works fine, but we want to be able to change compiler flags depending on the compiler being used: ie when using the Intel Compiler, we want to use /O3 in release builds rather than /O2.

I don’t want to have to go into the generated vcxproj files and do this manually, and need to find a neat and scalable way of doing this. So far I’ve been unable to. Trying to set the

CMAKE\_CXX\_FLAGS\_RELEASE

flag via the command line doesn’t work. I tried to create a toolchain file containing just:

set(CMAKE\_CXX\_FLAGS\_RELEASE\_INIT “${\_MD} /O3 /Ob2 /DNDEBUG”)

and then specifing this toolchain file with the -DCMAKE\_TOOLCHAIN\_FILE when calling cmake. However this results in the following entry in the cache:

CMAKE\_CXX\_FLAGS\_RELEASE:STRING=/O3 /Ob2 /DNDEBUG /O2 /Ob2 /DNDEBUG

It seems that line 481 of \<cmake\_install\_dir\>\Modules\Platform\Windows-MSVC.cmake is being applied AFTER my toolchain file is processed - this is the line:

```
  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT "${_MD} /O2 /Ob2 /DNDEBUG")

```

ie it’s appending “/O2 /Ob2 /DNDEBUG” those settings to what I already set. I don’t really know what to do - it seems whatever I try, the pre-baked settings contained in the cmake installation will always get applied after anything I try to set myself, meaning I need to somehow edit the vcxproj files myself after cmake is done with them.

What can I do?
