Today I was struggling with a relatively simple task in Visual Studio 2022: pass a file path in my source code folder to my running application. I am, as usual, using VS’s CMake mode, but also using conan 2.x and hence CMake presets. That last part is relevant, because apparently, it changes the way that .vs/launch.vs.json gets its data for macro support.
To make things a little more concrete, take a look at this, non-working, .vs/launch.vs.json:
{
"version": "0.2.1",
"defaults": {},
"configurations": [
{
"type": "default",
"project": "CMakeLists.txt",
"projectTarget": "application.exe (src\\app\\application.exe)",
"name": "application.exe (src\\app\\application.exe)",
"env": {
"CONFIG_FILE": "MY_SOURCE_FOLDER/the_file.conf"
}
}
]
}
Now I want MY_SOURCE_FOLDER in the env section there to reference my actual source folder. Ideally, you’d use something like ${sourceDir}, but VS 2022 was quick to tell me that it failed evaluation for that variable.
I did, however, find an indirect way to get access to that variable. The sparse documentation really only hints at that, but you can actually access ${sourceDir} in the CMake presets, e.g. CMakeUsersPresets.json or CMakePresets.json. You can then put it in an environment variable that you can access in .vs/launch.vs.json. Like this in your preset:
{
...
"configurePresets": [
{
...
"environment": {
"PROJECT_ROOT": "${sourceDir}"
}
}
],
...
}
and then use it as ${env.PROJECT_ROOT} in your launch config:
{
"version": "0.2.1",
"defaults": {},
"configurations": [
{
"type": "default",
"project": "CMakeLists.txt",
"projectTarget": "application.exe (src\\app\\application.exe)",
"name": "application.exe (src\\app\\application.exe)",
"env": {
"CONFIG_FILE": "${env.PROJECT_ROOT}/the_file.conf"
}
}
]
}
Hope this spares someone the trouble of figuring this out yourself!