visual-c++cmakedllctest

How to integrate CTest with Visual Studio?


I have been following the guide from:

However I fail to understand how to integrate the ctest mechanism in Visual Studio 2019. Right now my shared library (dll) is not found upon execution (only on Windows):

enter image description here

Here is the simple project setup:

> cat .\CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
project (p LANGUAGES C)
set(CMAKE_C_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
add_subdirectory ("src")
enable_testing()
add_subdirectory ("tests")

And then src is simply:

> cat .\src\CMakeLists.txt
add_library(foo SHARED foo.c foo.h)
target_include_directories(
  foo PUBLIC $<BUILD_INTERFACE:${p_SOURCE_DIR}/src>
)

finally tests is:

> cat .\tests\CMakeLists.txt
add_executable(footest footest.c)
target_link_libraries(footest PRIVATE foo)
add_test(NAME footest COMMAND footest)

Running the above under WSL works as expected:

$ make && make test
[ 50%] Built target foo
[100%] Built target footest
Running tests...
Test project /mnt/c/Users/malat/CMakeProject1/bin-gcc
    Start 1: footest
1/1 Test #1: footest ..........................   Passed    0.01 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.03 sec

Solution

  • A modern approach to this issue seems to TARGET_RUNTIME_DLLS:

    Documentation suggest to use:

    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
    )
    

    Watch out that the -t flag which seems to have been introduced lately.

    Reference:


    When using Visual Studio 2019, you may need to change the default cmake version used: