Home > Mobile >  How to properly link an installed library to the CMake in Windows?
How to properly link an installed library to the CMake in Windows?

Time:01-03

I have a CMake project that uses mosquittopp. It is properly running on Linux without needing any additional configurations (i.e. #include <mosquittopp.h> works without target_include_directories; and libraries are linked without find_library)

However, when I try the same on Windows, I am constantly having undefined reference problems. Here is the minimal reproducible example:

  1. Install mosquitto to the system; Here are some files from C:/Program Files/mosquitto:
├── libcrypto.dll
├── libssl.dll
├── mosquitto.dll
├── mosquitto.exe
├── mosquittopp.dll
├── devel
│   ├── mosquitto.h
│   ├── mosquitto.lib
│   ├── mosquittopp.h
│   └── mosquittopp.lib
  1. Write and save the following to main.cpp:
#include <iostream>
#include <mosquittopp.h>

int main() {
    std::cout << "hello world";

    mosqpp::lib_init();

    return 0;
}
  1. Create the following CMakeLists.txt file:

111

cmake_minimum_required(VERSION 3.15) 
project(sandbox LANGUAGES CXX)

add_executable(MainFile main.cpp)

target_include_directories(MainFile PUBLIC "C:/Program Files/mosquitto/devel")
target_link_libraries(MainFile "C:/Program Files/mosquitto/devel/mosquittopp.lib")


set_property(TARGET MainFile PROPERTY CXX_STANDARD 17)
set_property(TARGET MainFile PROPERTY CXX_STANDARD_REQUIRED On)
set_property(TARGET MainFile PROPERTY CXX_EXTENSIONS Off)

I tried to use different combinations of find_library(), absolute paths, adding and removing dll files, adding all lib files but to no avail.

EDIT: The error message in this example is:

[build] C:/Users/myuser/OneDrive/Desktop/test/main.cpp:6: undefined reference to `__imp__ZN6mosqpp8lib_initEv'
[build] collect2.exe: error: ld returned 1 exit status
[build] mingw32-make[2]: *** [CMakeFiles\MainFile.dir\build.make:101: MainFile.exe] Error 1
[build] mingw32-make[1]: *** [CMakeFiles\Makefile2:82: CMakeFiles/MainFile.dir/all] Error 2
[build] mingw32-make: *** [Makefile:90: all] Error 2

this is a minimal reproducible example, but the similar errors arise in the full project as well.

CodePudding user response:

I think I know where the issue is now after looking at the error message and checking out mosquitopp.

My current guess is that you've downloaded pre-compiled binaries from their download page.

These binaries were built using MSVC (2019) however you are using mingw32 to build your project. This is apparent from the line here:

[build] mingw32-make[2]: *** [CMakeFiles\MainFile.dir\build.make:101: MainFile.exe] Error 1

You cannot use different compilers, the binaries will always most likely be different. So you have two options now to solve this:

  • Build your own mosquittopp library using mingw32
  • Build your application using MSVC 2019
  • Related