Search code examples
c++qtqmakesubdirectory

Qt subdirs project with lib and app that uses the lib


I have created a Qt subdirs project which 2 projects - lib1 and app1, where app1 uses a class from lib1.

enter image description here

lib1:

Lib1::Lib1() {
    qDebug("hello, lib1");
}

app1 should print hello, lib1:

#include "lib1.h"
int main(int /*argc*/, char */*argv*/[]) {
    Lib1();
    return 0;
}

What is the canonical way to link the 2 projects so app1 can use lib1? I've looked at create and use shared library with qt and it mentions INCLUDEPATH, LIBS, and $$PWD. Is this what I should use and is it the most proper way to do it? Also, should I add app1.depends = lib1 to my subdirs.pro file?


Solution

  • You can use the libraries in each subproject by linking it to the subproject. You should add the target lib pathes to LIBS and INCLUDEPATH variables in the pro file. For simplicity this can be done by right clicking on the subproject and choosing "Add Library" and then "Internal Library". When you select one library from the list of subprojects, the linking configurations are added to the .pro automatically. It will be like :

    win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../Lib1/release/ -lLib1
    else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../Lib1/debug/ -lLib1
    else:unix: LIBS += -L$$OUT_PWD/../Lib1/ -lLib1
    
    INCLUDEPATH += $$PWD/../Lib1
    DEPENDPATH += $$PWD/../Lib1
    

    If you define app1.depends = lib1, Lib1 would be built always before app1 as it depends on the lib. So it's recommended to define it in your subdirs pro file.