Search code examples
c++visual-studio-codecmakecl

How can I use CMake on command line? - Windows


I want to run CMake on a Windows machine on the command line. The problem is that using Visual Studio as the generator works fine, but when using Ninja, CMake cannot find the specified compiler (cl.exe). I have been able to get around this by calling vcvarsall.bat x64 on the command line before I run the cmake command, but shouldn't there be an easier way? Microsoft's documentation seems to suggest that this is the proper way.

Is there a way to invoke vcvarsall.bat in a CMakePresets.json file? Alternatively, since I am using VS Code, is there a way to have presets for VS Code so I can select what development enviroment I want? Sort of like a presets.json file, but for VS Code?

I have tried adding cl.exe to my PATH, but whenever doing this, there are other environment variables that also need set up.

I should also mention that none of this setup process needs to be done on Linux. Is there any way for Windows to always be able to access the necessary c++ files?

Finally, my motivation for all of this is to eventually use Intel's c++ compiler (icx.exe). Thank you for your time and suggestions.

Here is what the not working configuration in my CMakePresets.json file looks like:

{
    "name": "Ninja - MSVC",
    "displayName": "Ninja - MSVC",
    "description": "Ninja with MSVC compiler",
    "binaryDir": "${sourceDir}/_build",
    "generator": "Ninja",
    "cacheVariables": {"CMAKE_C_COMPILER": "cl", "CMAKE_CXX_COMPILER": "cl"},
    "condition": {"type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows"},
    "vendor": {
        "microsoft.com/VisualStudioSettings/CMake/1.0": {
            "hostOS": "Windows"
        }
    }
}

Solution

  • I have found several workflows to simplify this process for me:

    1. I found that the comment by Alan Birtles is the most user friendly approach to improving my workflow. The recommendation was to use the CMake Tools extension for VS Code which easily scans your system for compilers and you can use options in the bottom bar of VS Code to set up your project. On top of this, there are a bunch of settings for the extension in VS Code to customize the tool to your needs. This is by far the easiest to use, and it is the easiest to implement across different platforms and users.

    2. The second option was to run CMake directly in a Visual Studio Developer Command Prompt, but the disadvantage of this approach compared to the first is that you still have to type out your CMake commands.

    3. The final option is to run vcvarsall.bat x64 on startup of VS Code with a tasks.json file, but this option requires that you specify the path of the bat file, which isn't always portable.