visual-studiocmakebuildninjaworking-directory

Set working directory for Visual Studio 2022 CMake projects with Ninja generator


I need a way to set debugger working directory for my Visual Studio 2022 CMake project with Ninja generator. Setting VS_DEBUGGER_WORKING_DIRECTORY target property doesn't work: only launch.vs.json editing works. I obviously need to set it from CMake side, because in case of editing launch file, I cannot save this setting for my GitHub repo.

Also I would like to say that setting that property does work only in case where I set Visual Studio 17 2022 generator and open my projects with .sln file instead of CMake Project in Visual Studio, but it is not what I want.


Solution

  • Generally there are 2 reasons why developers want to set the working directory.

    1.) Loading files.

    If that is your situation take a look at this question: From Visual Studio to CMake, how to set current working directory?

    I describe an approach that works with both the Visual Studio / Ninja generator.

    2.) Loading dlls.

    CMake 3.21 added functionality for this exact situation.

    $<TARGET_RUNTIME_DLLS:tgt> New in version 3.21.

    This generator expression can be used to copy all of the DLLs that a target depends on into its output directory in a POST_BUILD custom command using the cmake -E copy -t command. For example:

    find_package(foo CONFIG REQUIRED) # package generated by install(EXPORT)
    
    add_executable(exe main.c)
    target_link_libraries(exe PRIVATE foo::foo foo::bar)
    add_custom_command(TARGET exe POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy -t $<TARGET_FILE_DIR:exe> $<TARGET_RUNTIME_DLLS:exe>
        COMMAND_EXPAND_LISTS
    )
    

    Link to official documentation:

    https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html#genex:TARGET_RUNTIME_DLLS

    Let me know if neither approach works for you.