Detecting when CMake is run from VS Code
Discussed in https://github.com/microsoft/vscode-cmake-tools/discussions/4233
Originally posted by multiplemonomials January 12, 2025 Hi, I am the maintainer of mbed-ce/mbed-os, and we have functionality in our build system that automatically generates launch.json and tasks.json files (for the Cortex-Debug extension) when CMake runs. This has been working well for us, and it saves a ton of effort writing these files manually.
Where it gets tougher is that we need to detect whether CMake is being run from the command line directly, from VS Code, or from CLion, so that we know what type of run configurations should be generated. CLion provides the CLION environment variable which can be used to detect it, but I was not able to find a matching environment variable or CMake variable from this extension. Until now, our workaround was to look for the CMAKE_EXPORT_COMPILE_COMMANDS option, which is (was?) used by VS Code. However, it seems like this variable is not getting set anymore, at least when using CMake Presets instead of cmake-variants.yml.
So I wanted to ask, is there any better way that we can use in CMake to detect VS Code? If not, would it be possible to add one?
yeah, I'm also observing that CMAKE_EXPORT_COMPILE_COMMANDS isn't getting set when using presets.
Not sure if this will help, but you may be interested to check for a client-vscode directory under the .cmake directory in the top-level project's binary directory. That would probably actually tell you if CMake Tools is in the picture. It also seems that when CMake is run through VS Code, it inherits environment variables like VSCODE_PID (like bob mentioned), so in your CMakeLists.txt you could use if(DEFINED "ENV{VSCODE_PID}").
There are other ways to run CMake "within" VS Code, like using the integrated terminal. For that, see https://stackoverflow.com/q/57635562/11107541.
@multiplemonomials If you're doing this as part of the project configuration step, Copilot wrote this for me which may be of use:
execute_process(
COMMAND powershell -Command "$ppid = (Get-CimInstance Win32_Process -Filter \"ProcessId=$PID\").ParentProcessId; $gppid = (Get-CimInstance Win32_Process -Filter \"ProcessId=$ppid\").ParentProcessId; (Get-CimInstance Win32_Process -Filter \"ProcessId=$gppid\").Name"
OUTPUT_VARIABLE GRANDPARENT_PROCESS_NAME
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "Parent of parent process name: ${GRANDPARENT_PROCESS_NAME}")
It prints Code.exe on Windows.
If you enable debug for cmake.loggingLevel the extension should also print out the current environment for inspection, which I believe includes variables like: VSCODE_PID and VSCODE_CWD. These might also be useful for detecting if you're running in the VS Code environment.