CMake - Linking against a shared library using Qt6
-
Hello,
On a project using a shared library using Qt6, the compiler raise the LNK2001 error
unresolved external symbol
.
I am not a CMake expert so I start from the Qt example code here: https://doc.qt.io/qt-6/cmake-get-started.html that I modify to match my requirements.
I made a minimal project showing the problem.Here is the tree view:
- helloworld
- helloworld.hpp
- main
- main.cpp
- CMakeLists.txt
The helloworld.cpp file:
#pragma once #include <qobject.h> #include <iostream> class HelloWorld : public QObject { Q_OBJECT public slots: __declspec(dllexport) void hello() { std::cout << "Hello world!\n"; } };
The main.cpp file:
#include <helloworld.hpp> int main(int argc, char** argv) { HelloWorld helloworld; helloworld.hello(); }
The CMakeLists.txt file:
cmake_minimum_required(VERSION 3.16.0) project(helloworld VERSION 1.0.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) add_library(helloworld SHARED helloworld/helloworld.hpp) add_executable(main main/main.cpp) find_package(Qt6 COMPONENTS Core REQUIRED) target_link_libraries(helloworld PRIVATE Qt6::Core) target_link_libraries(main PRIVATE helloworld) target_include_directories(main PRIVATE "${helloworld_SOURCE_DIR}/helloworld") target_link_libraries(main PRIVATE Qt6::Core)
To generate the project, I use this command:
cmake -G "Visual Studio 16 2019" -B .\build\ -S . -DCMAKE_PREFIX_PATH="C:\Qt\6.1.0\msvc2019_64\"
And this is the errors I get:
main.obj : error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __cdecl HelloWorld::metaObject(void)const " (?metaObject@HelloWorld@@UEBAPEBUQMetaObject@@XZ) 1>main.obj : error LNK2001: unresolved external symbol "public: virtual void * __cdecl HelloWorld::qt_metacast(char const *)" (?qt_metacast@HelloWorld@@UEAAPEAXPEBD@Z) 1>main.obj : error LNK2001: unresolved external symbol "public: virtual int __cdecl HelloWorld::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@HelloWorld@@UEAAHW4Call@QMetaObject@@HPEAPEAX@Z) 1>G:\dev\test-qt-cmake\build\Debug\main.exe : fatal error LNK1120: 3 unresolved externals
Do you have an idea from what it could come from ?
Thanks in advance !
Loïc
- helloworld
-
@Loic-B said in CMake - Linking against a shared library using Qt6:
Do you have an idea from what it could come from ?
You don't export the library as needed and described here.
-
@Christian-Ehrlicher thanks for this quick reply, it works!