简体   繁体   中英

how to set Visual Studio CMake project run time environment variable?

Visual Studio 2022 CMake project

I build a qt cmake project in vs2022, everything works well, but when last step to run exe, it says the error of lack of dll files. I know that this is the problem of dll file directory. I can add it to system env path, or copy dll to exe file dir, but I guess that additional way that not mucks system env exists. I notice that VS traditional project can set debugger env in property, which set a local env variable, but I cannot find the way to set this in new support CMake Project in VS2022.

The IDE QtCreator also provide an analogous way that set env var for only project to run exe file, so any way to set this in VS like the traditional sln project , I search and find that some configure json file may help, but I cann't find precise setting.

As above, I guess some ways exist to set exe runtime env var to find dll file in VS CMake project , anyone could give me any tip, any helpful advice would be highly appreciated!

You can add the following properties to your CMakeLists.txt file that contains the executable target:

set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT <your_executable_target_name>)
set_property(TARGET <your_executable_target_name> PROPERTY VS_DEBUGGER_ENVIRONMENT "PATH=${QTDIR}/bin")

Finally, I find the way for cmake project without solutions in visual studio, find launch.vs.json file by this , add custom env variable path to json file, add following content to project in configurations key:

 "env": {
    "PATH": "<dll-file-path>"
 }

It works well for me, hope this can help you.

If you need a build system independent solution, adding a custom target that simply launches the program could be an option:

Helper script (run_program.cmake)

set(ENV{PATH} "${PATH}")
execute_process(COMMAND "${PROGRAM}")

Actual project

add_executable(MyProgram ...)

add_custom_target(RunMyProgram COMMAND ${CMAKE_COMMAND} -D "PROGRAM=$<TARGET_FILE:MyProgram>" -D "PATH=${QT_BINARY_DIR};$ENV{PATH}" -P ${CMAKE_CURRENT_SOURCE_DIR}/run_program.cmake)

This allows you to use eg

cmake --build build_dir --target RunMyProgram --config Release

after building to run the program with the modified PATH environment variable.


Another option would be to use add_test + ctest, to run the program with a modifier environment, but this could easily render real test cases unuseable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM