0

Newbee here on QT creator and CMake and apologies for the basic question but struggling to link simple external library to my main project. Here are the project paths:

build-QMLTest-Desktop_Qt_6_3_1_MinGW_64_bit-Debug   // application binary path
QMLLib
    build-mylib-Desktop_Qt_6_3_1_MinGW_64_bit-Debug // lib binary path
    mylib
        CMakeLists.txt
        mylib.cpp   // lib source path
        mylib.h
QMLTest
    CMakeLists.txt
    main.cpp    // application source path

Here is my how I am trying to link the static library (snipped of QMLTest/CMakeLists.txt). I am using this thread as reference:

How do I explicitly specify an out-of-tree source in CMake?

add_subdirectory(../QMLLib/mylib ../QMLLib/build-mylib-Desktop_Qt_6_3_1_MinGW_64_bit-Debug)

target_link_libraries(mylib)

set(PROJECT_SOURCES
        main.cpp
        qml.qrc
)

main.cpp

#include "../QMLLib/mylib/mylib.h"

int main(int argc, char *argv[])
{
    Mylib mylib;

Yet, it won't resolve, here is the output

C:/Qt/Tools/mingw1120_64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles/QMLTest.dir/main.cpp.obj: in function `qMain(int, char**)':
C:/myroot/UITest/QMLTest/main.cpp:13: undefined reference to `Mylib::Mylib()'
collect2.exe: error: ld returned 1 exit status

I could not get an answer, so 50 points for grabs, since I cannot resolve this issue.

Ideally if you can point me out to recent project using CMake and QT Creator 8.0 making a simple project and library and link them together, it would be great.

gmmo
  • 2,577
  • 3
  • 30
  • 56

2 Answers2

0

At first, try to separate the directories to add in the add_subdirectory command arguments to be sure that everything within the library subdirectories is compiled. Then use target_link_libraries command properly:

add_subdirectory(../QMLLib/mylib)
set(PROJECT_SOURCES
        main.cpp
        qml.qrc
)
include_directories(../QMLLib/mylib/include)
# Link subdir target AFTER definition of the project target
add_library(myproject ${PROJECT_SOURCES})
target_link_libraries(myproject mylib)

I suggest you refer to the actual CMakeLists.txt file I used when importing my library into the existing project (despite being ROS-based, CMake works the same way). Just extract the sequence of commands from there.

Andrei Vukolov
  • 118
  • 1
  • 10
  • It did now work for me, the add_subdirectory is asking for two parameters. One where the source is and the second where the binary for the library. I will study your project more carefully. It might be something really simple. – gmmo Oct 05 '22 at 16:40
  • 1
    @gmmo the second parameter is optional unless there is no `CMakeLists.txt` in the subdirectory. – Andrei Vukolov Oct 05 '22 at 17:10
0

I ended up re-arranging the folders and the solution is here:

Cannot add library source to cmake project on QT

where I just include the sources from a separate library project

gmmo
  • 2,577
  • 3
  • 30
  • 56