Issue
I've been trying to migrate my current visual studio project to use CMake, the CMakeConverter did an awesome job producing a nice CMakeLists.txt file, and build was successfully. As my code needs to load ini and txt files from the source directory, it gives me a series of problems. When running visual studio solution debugger, it uses the directory where main.c is in the source code $myproject. However, when debugging with cmake build, it moves to the subdirectory $myproject\x64\Debug, and thus failed to locate the ini and txt files.
So my question is, how can I set the current working directory for Cmake build to be the same as when I run debugger in visual studio without Cmake? Or is it possible to add the ini and txt files to the debug directory where Cmake runs?
Solution
Or is it possible to add the ini and txt files to the debug directory where Cmake runs?
Yes it's possible. Here is a simplified example.
add_executable(foobar)
target_sources(foobar PRIVATE main.cpp)
# After foobar has finished building, copy foobar.txt and foobar.ini to the directory of foobar
add_custom_command(TARGET foobar POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_LIST_DIR}/foobar.txt $<TARGET_FILE_DIR:foobar>
COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_LIST_DIR}/foobar.ini $<TARGET_FILE_DIR:foobar>
)
This approach is cross-platform and simple.
how can I set the current working directory for Cmake build to be the same as when I run debugger in visual studio without Cmake?
You can set the relevant visual studio debugger properties. CMake gives you the ability to set these properties if you need to.
See this stackoverflow post if you are interested.
However, I personally think the first approach shown above is superior.
Answered By - jpr42 Answer Checked By - Mary Flores (WPSolving Volunteer)