How to use dynamic link library with CMake?
Solution 1
Your modelling of the dynamic library is incorrect, both on CMake and on the source level.
As a starting point, try building the dll as part of the same CMake project as the consuming executable:
cmake_minimum_required(VERSION 3.5)
project(test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(GenerateExportHeader)
add_library(power SHARED power_sources.cpp power.h)
generate_export_header(power)
target_include_directories(power PUBLIC ${PROJECT_BINARY_DIR} ${PROJECT_SOURCE_DIR})
add_executable(test main.cpp)
target_link_libraries(test PRIVATE power)
Note the use of the generate_export_header
function, which instructs CMake to generate macros for exporting functions on shared library interfaces in a portable way. Since generated files go to the binary directory tree, we have to adjust the include directories for the library accordingly.
To make sure the function gets properly exported, change your header as follows:
#ifndef POWER_H
#define POWER_H
#include <power_export.h>
POWER_EXPORT double power(double number) noexcept;
#endif // POWER_H
Note that generare_export_header
allows you to customize the generated export header extensively.
Be sure you get the project to build and run from this baseline.
If you want to build the dll externally (which is not strictly necessary, but since that's what your question is about...), we have to modify the CMake file to something like:
cmake_minimum_required(VERSION 3.5)
project(test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(power)
add_executable(test main.cpp)
target_link_libraries(test PRIVATE power)
With all the magic here happening in the find_package
call. That call is now responsible for providing all the information that was previously handled by the lines for building the library:
- Providing of an imported target
power
for consumption by thetarget_link_libraries
call - Association of the library name of the import library (the
power.lib
file) via that imported target - Exposure of the public include directories for both
power.h
andpower_export.h
via that imported target
You can either construct such an imported target manually in the find script, or have CMake do it for you. In the first case, create a FindPower.cmake
script file, make sure it's location is part of the CMAKE_MODULE_PATH
and write the code for finding the library and header files and constructing the imported target in there. Note that getting this right in a portable way can be very tricky and goes far beyond the scope of a StackOverflow question. In the second case, have the CMake script that builds the power
library perform an install step during which a config file package will get generated, which can then be consumed by your test
project. Note that this approach is not viable if the power
library is not itself being built with CMake, so in that case you will have to stick with the first option.
Solution 2
Dynamic linking in Windows requires that externally visible symbols are declared with the keyword __declspec
. Your header "power.h" should be modified:
#ifndef POWER_H
#define POWER_H
#if defined(__WIN32__) && !defined(__CYGWIN__)
# if (defined(_MSC_VER) || defined(__MINGW32__)) && defined(BUILD_DLL)
# define POWERAPI __declspec(dllexport)
# elif (defined(_MSC_VER) || defined(__MINGW32__))
# define POWERAPI __declspec(dllimport)
# endif
#endif
POWERAPI double power(double number) noexcept;
#endif // POWER_H
In the project building the DLL power.dll with CMake, you should define the symbol BUILD_DLL:
add_definitions(-DBUILD_DLL)
then it should generate a power.lib file when the MSVC compiler and a power.a when using MINGW. Don't define BUILD_DLL in the project using the DLL, and it should work.
Related videos on Youtube

Nima Ghorab
I am a FX TD and programmer! My main concentration is C++. I worked with Eigen, Qt/QML and OpenCV as a third party library. I also have knowledge about Python and using it to create some scripts.
Updated on June 04, 2022Comments
-
Nima Ghorab 7 months
I have simple program as follow:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.5) project(test LANGUAGES CXX) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) LINK_DIRECTORIES(${PROJECT_SOURCE_DIR}) add_executable(test main.cpp) target_include_directories(test PRIVATE ${PROJECT_SOURCE_DIR}) target_link_libraries(test PRIVATE power.dll)
main.cpp:
#include <iostream> #include "power.h" using namespace std; int main() { cout << "Hello World!" << endl; power(4.); return 0; }
power.h:
#ifndef POWER_H #define POWER_H double power(double number) noexcept; #endif // POWER_H
Implementation of
power.h
is in a .dll namedpower.dll
. If I compile this project with MinGW 7.3.0 X64 says:error: undefined reference to `power(double)'
If I compile it with MSVC 2017 X64 says:
error: LNK1104: cannot open file 'power.lib'
both errors show that
power.dll
can't detect by the linker. I did many searches but none of solutions worked for me! Can anyone help about this? Thanks in advance!-
Tsyvarev about 3 yearsOn Windows linking with a library is performed using
.lib
file..dll
is used at runtime only. Also, make sure thatpower
function is exported from the library.
-
-
Nima Ghorab about 3 yearsDear @Pedro, it did not work! It gives this error now: error: BUILD_DLL: No such file or directory
-
Former contributor about 3 yearsSorry, small mistake. The add_definitions() macro must be added to the project that builds the DLL, not the one using the DLL.
-
Former contributor about 3 yearsIf you can't rebuild the DLL, then you should explore other options.
-
Nima Ghorab about 3 yearsDear @Pedro it is still not working! If I use MinGW says: error: undefined reference to `power(double)' and MSVC says: power.h:12: error: C2144: syntax error: 'double' should be preceded by ';' and also: power.h:12: error: C4430: missing type specifier - int assumed. Note: C++ does not support default-int
-
Nima Ghorab about 3 yearsDear @Pedro if I have only .lib file without having power.cpp and power.dll can I convert power.lib to power.dll?
-
Nima Ghorab about 3 yearsDear @ComicSansMS thanks a lot for the great answer. How OpenCV, Boost and ... work so that we can link our program to dll of these libraries directly? How do they handle this problem?
-
ComicSansMS about 3 years@NimaGhorab They do the same as what I described in the answer. Find scripts for Boost ship as part of CMake (approach #1), but you could just as easily write such a script yourself. OpenCV provides a config file script as part of its installation (approach #2).
-
Nima Ghorab about 3 yearsThanks a lot man! As my final question why we should link to .dll file when using opencv (not .lib) in following example? Because I read in many posts that linking against dll files in such way is wrong! Linking to dynamic library using QMake
-
ComicSansMS about 3 years@NimaGhorab Short answer: MinGW treats dynamic libraries in a weird (ie. non-Windows-y) way, mainly due to the fact that its model of shared libraries is influenced largely by Linux
.so
files. Shared libraries on Windows differ a lot from shared libraries on Linux. Most of the confusion regarding how to integrate shared libraries with a portable build system like CMake is usually due to the fact that people only understand how they work on one of those systems, but not the other.