How to Programmatically Generate CMake Cache in VS CMake Open Folder project

Vivek Pandey 5 Reputation points
2024-03-22T06:01:21.6433333+00:00

We want to programmatically achieve the same output for "Generate Cache" as is done in Visual Studio IDE via "Project->Generate Cache" for our CMake project. Is there any API available which I can use in my VS extension written in C-Sharp.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,402 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Arpit Verma 0 Reputation points
    2024-07-22T13:54:49.4566667+00:00

    To programmatically generate a CMake cache in a VS CMake Open Folder project, follow these steps:

    1. Create a CMakeSettings.json file:
      • In your project folder, create a new file named CMakeSettings.json.
      • This file will contain the CMake settings and cache configuration.
    2. Configure the CMake cache:
      • In CMakeSettings.json, add the following configuration:
    
    {
    
      "configurations": [
    
        {
    
          "name": "YourConfigName",
    
          "generator": "Ninja",
    
          "cacheRoot": "${env.USERPROFILE}/.cmake/YourCacheName",
    
          "cacheEntries": [
    
            {
    
              "key": "CMAKE_CXX_COMPILER",
    
              "value": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.34.31933/bin/Hostx64/x64/cl.exe"
    
            },
    
            {
    
              "key": "CMAKE_C_COMPILER",
    
              "value": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.34.31933/bin/Hostx64/x64/cl.exe"
    
            }
    
          ]
    
        }
    
      ]
    
    }
    
    
    
    * Update the `CMAKE_CXX_COMPILER` and `CMAKE_C_COMPILER` values to your desired compiler paths.
    
    
    1. Run CMake to generate the cache:
      • Open a command prompt or terminal in your project folder.
      • Run the following command:
    
    cmake -S . -B build -G "Ninja" -DCMAKE_USER_MAKE_RULES_OVERRIDE="CMakeSettings.json"
    
    
    
    
    1. Use the generated cache in VS:
      • Open your project in Visual Studio.
      • Go to File > Open > Folder... and select your project folder.
      • VS will detect the generated CMake cache and use it for building and IntelliSense.

    By following these steps, you can programmatically generate a CMake cache for your VS CMake Open Folder project.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.