Here is the short version with a quick setup of the situation and the fix. After that, I’ll elaborate a bit.
TL;DR
Setup
I have a custom C++ library and a separate project for tests (all based on Qt 6). The test project requires the library for execution.
Here is a short excerpt of the CMake scripts, first the library, then the tests.
project(wt2-shared VERSION 2.0.0 DESCRIPTION "WorkTracker2 Shared
Library")
# To export symbols.
add_compile_definitions(WT2_LIBRARY)
# Snip header + source definitions
add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS})
target_include_directories(${PROJECT_NAME} PUBLIC include/)
target_link_libraries(wt2-shared Qt6::Core Qt6::Sql)
project(wt2-shared-test VERSION 2.0.0 DESCRIPTION "WorkTracker2
Shared Library Tests")
# Snip header + source definitions
add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})
target_include_directories(${PROJECT_NAME} PRIVATE ${INCLUDES})
target_link_libraries(${PROJECT_NAME} Qt6::Core Qt6::Test wt2-shared)
Error
This error only occurred on Windows, and it does not matter which toolchain I used, be it MinGW or MSVC. The result was always the same.
The following shows the MinGW error.
[100%] Linking CXX executable wt2-shared-test.exe
CMakeFiles\wt2-shared-test.dir/objects.a(testdatasource.cpp.obj):testdatasource.cpp:(.text+0x3e5):
undefined reference to `__imp__ZN4Data3Sql13SqlDataSourceC1E7QString'
CMakeFiles\wt2-shared-test.dir/objects.a(testdatasource.cpp.obj):testdatasource.cpp:(.text+0x401):
undefined reference to `__imp__ZN4Data3Sql13SqlDataSource4loadEv'
CMakeFiles\wt2-shared-test.dir/objects.a(testdatasource.cpp.obj):testdatasource.cpp:(.text+0x514):
undefined reference to `__imp__ZN4Data3Sql13SqlDataSourceC1E7QString'
CMakeFiles\wt2-shared-test.dir/objects.a(testdatasource.cpp.obj):testdatasource.cpp:(.text+0x530):
undefined reference to `__imp__ZN4Data3Sql13SqlDataSource4loadEv'
collect2.exe: error: ld returned 1 exit status
mingw32-make[2]: ***
[wt2-shared-test\CMakeFiles\wt2-shared-test.dir\build.make:142:
wt2-shared-test/wt2-shared-test.exe] Error 1
Solution
The add_library
definition in the CMakeLists.txt was incomplete.
To make it work, I added SHARED
because I want a shared library.
add_library(${PROJECT_NAME} SHARED ${SOURCES} ${HEADERS})
Continue reading, though, to get the full picture. There is more to it than just making the library a shared one.