I have a program I want to build in Visual Studio 2017 and I also want CMake to generate my proj/sln files, thus I'm using CMake 3.8.2 on Windows10 with visual studio generator 2017 amd64.
Thing is, my program needs different libraries to be linked against when building in Debug or in Release, I want the generated VS proj to correctly select the right libraries to link when switching configuration inside Visual Studio. This can easily be achievable by manually editing the proj files but I want CMake to do it for me.
In CMakeLists.txt I collected the relevant libraries in two lists LIBS_DEBUG
and LIBS_RELEASE
, so far I tried the followings:
target_link_libraries(MyProgram debug ${LIBS_DEBUG} optimized ${LIBS_RELEASE})
This does not work since it generates both options to appear in both configurations inside VS.
target_link_libraries(MyProgram $<$<CONFIG:Debug>:${LIBS_DEBUG}>
$<$<CONFIG:Release>:${LIBS_RELEASE}>)
I never used generator-expressions so I'm not sure the above is correct but I "copied" it from the docs. Anyway it does not work since it makes appear both libraries set in both configurations.
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
target_link_libraries(MyProgram ${LIBS_DEBUG})
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Release")
target_link_libraries(MyProgram ${LIBS_RELEASE})
endif()
This also does not work because it produces empty configuration sets.
Finally the question: What is the correct/optimal way to generate a "programmable" linking based on Visual Studio Configurations?
After some more digging, I can answer myself, I'll post the answer for others that might stumble into this problem.
Method 2 is the correct answer, however, it was not working because of the list variable LIBS_DEBUG
and LIBS_RELEASE
.
It appears that list expansions are not fully working within a generator-expression, I found an old bug that might be related.
The solution is to expand the list yourself, then call the generator-expression on each element of the list. This solution worked for me:
foreach(DL ${LIBS_DEBUG})
target_link_libraries(MyProgram
$<$<CONFIG:Debug>:${DL}>)
endforeach()
foreach(RL ${LIBS_RELEASE})
target_link_libraries(MyProgram
$<$<CONFIG:Release>:${RL}>)
endforeach()
It might not be that elegant but works perfectly.