CMake Visual Studio Debug/Release find_package - c++

I use cmake to build on Windows, Linux, and OSX. On Windows, I use .dll and .lib files that I have prebuilt and put it in a folder project/windows/bin, project/windows/include, and project/windows/lib. These folders house all my third party dependencies for windows. In my CMakeLists.txt, I use:
if(WIN32)
set(CMAKE_PREFIX_PATH ${PROJECT_SOURCE_DIR}/windows)
endif()
find_package(SDL2 REQUIRED)
find_package(GLEW REQUIRED)
It works but I am only able to use one configuration of the library. I would like to be able to link different configuration of the library like Debug and Release.
The question is :
How do I make it so that when I set my visual studio project to debug, it will use the debug version of the library and use the release version of the libray when I set the visual studio project to release?
Do I need to set up my /windows library directory differently?
Thanks in advance

I'm now sure, whether the FindSDL2 and FindGLEW modules you use provide imported targets. If so, then might pick up the respective library as both debug and release and you should use the imported target for linking.
Otherwise, you have two options:
Explicitly use optimized <LIB1_release> debug <LIB1_debug> as referenced by #aichao in the other SO question/answer:
target_link_libraries(MyConsumerTarget
PUBLIC optimized <LIB1_release>
debug <LIB1_debug>)
Manually create imported library targets for each external library and use them for linking:
if(NOT TARGET External::lib1) # this if is required for subsequent runs of CMake
add_library(External::lib1 SHARED IMPORTED GLOBAL)
set_target_properties(External::lib1
PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${PROJECT_SOURCE_DIR}/windows/include"
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION_RELEASE "${PROJECT_SOURCE_DIR}/windows/bin/<LIB1_release>.dll"
IMPORTED_IMPLIB_RELEASE "${PROJECT_SOURCE_DIR}/windows/lib/<LIB1_release_importlib>.lib"
IMPORTED_LOCATION_DEBUG "${PROJECT_SOURCE_DIR}/windows/bin/<LIB1_debug>.dll"
IMPORTED_IMPLIB_DEBUG "${PROJECT_SOURCE_DIR}/windows/lib/<LIB1_debug_importlib>.lib")
endif()
target_link_libraries(MyConsumerTarget
Public External::lib1)
Personally, I prefer the latter as it is less verbose in the main CMakeLists file. The definition of the different libraries can be done in other files included via other means.
Usually, I have a directory 3rdparty in my projects with a CMakeLists.txt file, which pulls in external projects and defines such imported targets. In the main CMake file I can then easily use these imported targets.

Related

cmake doesn't recognize dependency on static lz4 [duplicate]

I have a program that depends on an external library (SDL for example). I want CMake to take care of that dependency for me, so I was looking into FetchContent. As far as I understand, this module simply downloads the source code so that information on the external library is available at configure time. For example:
include(FetchContent)
FetchContent_Declare(sdl
GIT_REPOSITORY <...>
)
FetchContent_GetProperties(sdl)
# sdl_POPULATED, sdl_SOURCE_DIR and sdl_BINARY_DIR are ready now
if(NOT sdl_POPULATED)
FetchContent_Populate(sdl)
endif()
At some point, however, I want to build that source code and link it to my main executable. How to do it the "modern CMake way"?
The recommended way to build external libraries from source as part of your build depends on what the external lib provides build-wise.
External lib builds with cmake
If the external lib builds with cmake then you could add the lib to your build via a add_subdirectory(${libname_SOURCE_DIR}) call. That way cmake will build the external lib as a subfolder ("subproject"). The CMakeLists.txt file of the external lib will have some add_library(ext_lib_name ...) statements in it. In order to then use the external lib in your targets (an application or library that depends on the external lib) you can simply call target_link_libraries(your_application <PRIVATE|PUBLIC|INTERFACE> ext_lib_name) https://cmake.org/cmake/help/latest/command/target_link_libraries.html
I had a quick look at this github repo https://github.com/rantoniello/sdl - (let me know if you are referring to another library) and it actually looks like it is building with cmake and that it allows clients to statically or dynamically link against it: https://github.com/rantoniello/sdl/blob/master/CMakeLists.txt#L1688-L1740
So, ideally your applicaiton should be able to do
add_executable(myapp ...)
target_link_libraries(myapp PRIVATE SDL2-static) // Statically link againt SDL2
Due to their CMakeLists.txt file the SDL2-static comes with properties (include directories, linker flags/commands) that will automatically propergate to myapp.
External lib does not build with cmake
If a external lib doesn't build with cmake then one can try to use add_custom_target https://cmake.org/cmake/help/latest/command/add_custom_target.html to build the library. Something along the lines of:
add_custom_target(myExternalTarget COMMAND <invoke the repo's build system>)
You'd then need to set the target properties that are important for clients yourself via the the proper cmake functions set_target_properties, target_include_directories ... A great writeup how to get started with these kinds of things: https://pabloariasal.github.io/2018/02/19/its-time-to-do-cmake-right/

VisualStudio CMake dynamic library: include/link all used functions in *single* dll

I have a VisualStudio-2019 C++ Project which uses CMake and Ninja to build a dll, the Project uses functions from a few Libraries like protobuf and spdlog, which I have installed using vcpkg.
When building, the output gets written to four distinct dll files and all of them are needed for the main-dll to run.
Below are two screenshots: left the current state and right the expected state.
The main.dll file should include all the functions it imports, the compiler shouldn't create separate dlls for each library.
I don't know knob I need to turn, I can imagine several ways to edit:
The C++ Code of the Project (Classes, inlining functions ?)
The CMakeList.txt
The Arguments of MSVC (compiler, linker flags)
The Arguments of Ninja
Where should I start ?
Setting the mentioned flags or appending -static to the import library components had no effect, I went as far as
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "-static")
set(CMAKE_MODULE_LINKER_FLAGS "-static")
set(CMAKE_SHARED_LINKER_FLAGS "-static")
set(CMAKE_STATIC_LINKER_FLAGS "-static")
But this didn't help a bit.
As it turned out this is a problem with vcpkg:
I had installed the packages with the triplet x64-windows, which builds for dynamic linkage, installing the packages with
vcpkg install --triplet=x64-windows-static protobuf spdlog makes static linking possible. If the static variants are not installed, the build proceeds silently with the dynamic ones.

Linking both third party precompiled dynamic and static libaries in Windows

Lately, I have been using cmake as a generator for my projects. I have successfully generated many vtk and other application projects. However, I now face a problem when trying to link both dynamic and static precompiled libraries. In particular, I have been given some dynamic precompiled third party dlls along with their respective .lib files. Furthermore, I am trying to link some static precompiled libraries (only .lib files) to my project so as to check the software licences.
Let say that my project is called test_example and I have some precompiled dynamic libraries in libs directory. The structure of my project directory is:
Test_example
-/include
-/libs
-/build
-CMakeLists.txt
The CMakeLists.txt for linking the dynamic libaries has the following content:
cmake_minimum_required(VERSION 2.8.9)
project (test_example)
set(CMAKE_BUILD_TYPE Release)
#For the shared libraries:
set (PROJECT_LINK_LIBS dynamic_1.dll dynamic_2.dll )
set (PROJECT_LINK_DIR ${test_example_SOURCE_DIR}/libs/)
set (PROJECT_INCLUDE_DIR ${test_example_SOURCE_DIR}/include/)
link_directories(${PROJECT_LINK_DIR})
include_directories(${PROJECT_INCLUDE_DIR})
add_executable(test_example test_example.cpp)
target_link_libraries(test_example ${PROJECT_LINK_LIBS})
When I generate the project with this cmake lists, I can successfully use methods from the precompiled dlls. However, I have not found a way to link against my static libraries, as well. Let say I have one static library which is called test_licence.lib. Should I drop it in the libs folder as well and simply refer to it like I do with the dynamic? When I do so and when opening my project solution in Visual Studio, I can see that both dynamic and static libraries have been added to Linker-->Input-->Additional DEpendencies. However, when I am trying to build the project, I have unresolved external dependencies which are methods from the static lib.
Does any of you have any idea what would be the most efficient way to accomplish that? Many thanks in advance!
There is a couple of issues here.
Unlike to what you may be used to from VS, CMake prefers absolute paths for linking, instead of setting a link directory and giving the relative path.
Also, you do not link against .dll files. Dlls are loaded at runtime, not at link time. Many dlls are shipped with import libraries (with a .lib ending), that handle the runtime loading automatically for you. These are the ones you should link against.
Also try not to hardcode libraries in CMake code. The problem here is that if something goes wrong, you end up with a cryptic linker error. You should use find_library instead, which will usually make CMake complain early if something is off.
A cleaner version of your CMake script would be something like
cmake_minimum_required(VERSION 2.8.9)
project (test_example)
# note setting the build type does nothing on a visual studio build
# and should probably be left to the user for other generators
set(CMAKE_BUILD_TYPE Release)
#For the shared libraries:
# this call will succeed if it finds a dynamic_1.lib file
find_library(DYNAMIC_LIB1 dynamic_1 HINTS ${test_example_SOURCE_DIR}/libs)
if(NOT DYNAMIC_LIB1)
message(FATAL_ERROR "Library dynamic_1 was not found!")
endif()
find_library(DYNAMIC_LIB2 dynamic_2 HINTS ${test_example_SOURCE_DIR}/libs)
if(NOT DYNAMIC_LIB2)
message(FATAL_ERROR "Library dynamic_2 was not found!")
endif()
# for the static libraries:
# basically the same; again this looks for a static_1.lib file
find_library(STATIC_LIB1 static1 HINTS ${test_example_SOURCE_DIR}/libs)
if(NOT STATIC_LIB1)
message(FATAL_ERROR "Library static_1 was not found!")
endif()
set (PROJECT_INCLUDE_DIR ${test_example_SOURCE_DIR}/include/)
include_directories(${PROJECT_INCLUDE_DIR})
add_executable(test_example test_example.cpp)
target_link_libraries(test_example ${DYNAMIC_LIB1} ${DYNAMIC_LIB2} ${STATIC_LIB1})
Double check in Visual Studio that all libraries were added as linker inputs, as expected. If you still get linker errors, it means that something is wrong with your third-party .lib file. Open a new question with the exact linker error that you get.
Here is how we are doing it:
Firstly, use add_library with final arguments STATIC IMPORTED. Then subsequently use set_property to set the IMPORTED_LOCATION property, which is a path to the built library. For example, we pull in gtest like so:
add_library(gtest UNKNOWN IMPORTED)
set_property(TARGET gtest PROPERTY IMPORTED_LOCATION ${binary_dir}/googlemock/gtest/${CMAKE_FIND_LIBRARY_PREFIXES}gtest.a)
Then, gtest is a known library in your build system and you can link with it normally later on by just doing
target_link_libraries(target-name gtest)
See also: Cmake imported libraries documenation

propagate dependencies to header-only ExternalProject with cmake

I'm trying to build a header-only library using CMake (Microsoft/GSL), in such a way that I can use variables like GSL_INCLUDE_DIRS and GSL_LIBRARIES to link to the target and propagate the appropriate dependencies.
The project I'm working on has a TON of sub-directories, and all the external projects are built in their own sub-directories, hence why the variables are important.
I'm using CMake 3.2.3
Typically (for a library with an actual .lib or .a) I'd do something like:
SET(TARGET_NAME gsl)
include(ExternalProject)
ExternalProject_Add(
${TARGET_NAME}-ext
URL "http://target/url"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
) # download/unzip the header-only project
# Specify include dir
SET(${TARGET_NAME}_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/include CACHE STRING "${TARGET_NAME} include directory")
# Library
add_library(${TARGET_NAME} SHARED IMPORTED GLOBAL)
SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES
IMPORTED_LOCATION "some/path/to/some/lib"
)
add_dependencies(${TARGET_NAME} ${TARGET_NAME}-ext)
SET(${TARGET_NAME}_LIBRARIES ${TARGET_NAME} CACHE STRING "${TARGET_NAME} library location")
MARK_AS_ADVANCED(${TARGET_NAME_UPPER}_DIR ${TARGET_NAME_UPPER}_INCLUDE_DIRS ${TARGET_NAME_UPPER}_LIBRARIES)
The problem here is that the header-only library has no lib to set the imported path for, so I can't use an IMPORTED library. If I don't use a library at all, then I can't set the dependencies in other modules on GSL without building (i.e. downloading/unzipping) every single time, which I don't want to do. a custom_target would have the same problem, so that's a no-go.
I think what I want is an interface library, something like
add_library(${TARGET_NAME} INTERFACE)
add_dependencies(${TARGET_NAME} ${TARGET_NAME}-ext)
but then cmake complains that
CMake Error at 3rdParty/gsl/CMakeLists.txt:33 (add_dependencies):
add_dependencies Cannot add target-level dependencies to INTERFACE library
target "gsl".
Is there someway I can use the interface library (or something) to propagate the dependency on the external project?
Disallowing dependencies on INTERFACE libraries was an oversight that was corrected in CMake version 3.3. After upgrading to the latest-stable release, I was able to use the methodology described in the question, and it worked exactly as desired.

"No rule to make target" error in cmake when linking to shared library

In Ubuntu, I have downloaded a third-party shared library, mylibrary.so, which I have placed in the directory /home/karnivaurus/Libraries. I have also placed the associated header file, myheader.h, in the directory /home/karnivaurus/Headers. I now want to link to this library in my C++ code, using CMake. Here is my CMakeLists.txt file:
cmake_minimum_required(VERSION 2.0.0)
project(DemoProject)
include_directories(/home/karnivaurus/Headers)
add_executable(demo demo.cpp)
target_link_libraries(demo /home/karnivaurus/Libraries/mylibrary)
However, this gives me the error message:
:-1: error: No rule to make target `/home/karnivaurus/Libraries/mylibrary', needed by `demo'. Stop.
What's going on?
While the other answer posted here is valid, it is out-dated. CMake now provides better solutions for using a pre-built external library in your code. In fact, CMake itself even discourages the use of link_directories() in its documentation.
The target_link_libraries() command takes very specific syntax for linking to an external library. A more modern solution is to create an IMPORTED CMake target for your external library:
add_library(MyExternalLib SHARED IMPORTED)
# Provide the full path to the library, so CMake knows where to find it.
set_target_properties(MyExternalLib PROPERTIES IMPORTED_LOCATION /home/karnivaurus/Libraries/mylibrary.so)
You can then use this imported CMake target later on in your code, and link it to your other targets:
target_link_libraries(demo PRIVATE MyExternalLib)
For other ways to use an external third-party library in your CMake code, see the responses here.
You may use a full path to the static library. To link w/ dynamic one, better to use link_directories() like this:
cmake_minimum_required(VERSION 2.0.0)
project(DemoProject)
include_directories(/home/karnivaurus/Headers)
link_directories(/home/karnivaurus/Libraries)
add_executable(demo demo.cpp)
target_link_libraries(demo mylibrary)
and make sure mylibrary has prefix lib and suffix .so in file name (i.e. full name is /home/karnivaurus/Libraries/libmylibrary.so).
To make you project more flexible, you'd better to write a finder module and avoid hardcode paths like /home/karnivaurus/*