There are so many ways to set the compiler in CMake. (CMAKE_CXX_COMPILER, CXX, etc)
What takes precedence?
- CXX
- CMAKE_CXX_COMPILER
- etc
There are so many ways to set the compiler in CMake. (CMAKE_CXX_COMPILER, CXX, etc)
What takes precedence?
After using CMake for a year I just ended up asking the devs.
Here is the answer they provided on discourse:
This is ordered in terms of most specific to least specific.
This variable must be set before the very first project call in your cmake project.
To be clear the toolchain file will just be setting CMAKE_<LANG>_COMPILER inside the file. It would be more correct to say that a toolchain could change the ways for setting a compiler.
These variable must be set before the very first project call in your cmake project.
You can also specify your compilers by setting environment variables.
CC specifies the C compiler: https://cmake.org/cmake/help/latest/envvar/CC.html
CXX specifies the CXX compiler: https://cmake.org/cmake/help/latest/envvar/CXX.html?highlight=cxx
As a last resort CMake tries to check your path and searches for known/common binary names in the PATH.
Having things in your path can also shorten the above commands so you don't have to use absolute paths.
For example if clang++ is in your path you can also do this.
cmake -S . -B build -D CMAKE_CXX_COMPILER=clang++
The above advice is only intended for command-line generators. (Ninja, Unix Makefiles, etc)
The VS generator doesn't pay attention to CMAKE_<LANG>_COMPILER, so setting it does nothing for that generator.
Visual Studio handles things slightly differently. Because of course it does. It's Visual Studio. Visual studio plays by it's own rules because it likes to make everything difficult.
Visual Studio is designed around toolsets.
Toolsets files are essentially how Visual Studio solutions describe the compiler/linker.
You can find your toolchains on your computer if you want.
Here is where they are located on my machine.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Microsoft\VC\v160\Platforms
CMake gives you the ability to specify the toolsets and architecture you are targeting via Visual Studio.
See the necessary CMake documentation here:
What an oddly specific question that now has an answer: https://learn.microsoft.com/en-us/cpp/build/cmakesettings-reference?view=msvc-160
The Visual Studio team has added official CMake support. So you can use Visual Studio with CMake in a much less annoying way.
DuckDuckGo or Google "CMake projects in Visual Studio"