简体   繁体   中英

Cannot add library source to cmake project on QT

I need to resolve a simple issue with a test project. However despite my attempts to look at stack overflow I cannot resolve it. The toy project has one main CMakeLists and two sub-folders. One mathlib and one is a unittest.

CMakeLists.txt
├───QTMathLib
└───QTUnitTest

the sources:

testmathlib.cpp

#include "testmathlib.h"
#include <QDebug>

TestMathLib::TestMathLib()
{
    qDebug() << __FILE__ <<" Created!";
}

int32_t TestMathLib::Add(int32_t a, int32_t b)
{
    return a+b;
}

tst_testadd.cpp

void TestAdd::initTestCase()
{
    TestMathLib testMathLib;
    int32_t result = testMathLib.Add(10, 20);

    qDebug() << "Result =" << result ;
    QVERIFY(30 == result);
}

However I want the UnitTest project to include the mathlib sources as below:

Add library to Cmake project

I tried this:

set (sources2
  ../QTMathLib/testmathlib.cpp
)
add_executable(TestAdd
    tst_testadd.cpp
)
add_library( mylib ${sources2} )
add_test(NAME TestAdd COMMAND TestAdd)
target_link_libraries(TestAdd PRIVATE Qt${QT_VERSION_MAJOR}::Gui
    Qt${QT_VERSION_MAJOR}::Test
    Qt${QT_VERSION_MAJOR}::Core
    mylib)

But this always give me a building error since I cannot resolve QDebug.h header file. Notice that other includes may be added, so don't just patch for the QDebug.h, assume any QTCore header can be included in the future.

D:\gmmo\qt_qml\QTTest\QTMathLib\testmathlib.cpp:2: error: QDebug: No such file or directory
D:/gmmo/qt_qml/QTTest/QTMathLib/testmathlib.cpp:2:10: fatal error: QDebug: No such file or directory
    2 | #include <QDebug>
      |          ^~~~~~~~

The fix should be on these files, not the source file itself.

└───QTUnitTest\CMakeLists.txt
├───QTMainApp\CMakeLists.txt

Any clues why it cannot file QT headers?

thank you #273K for the help, this worked:

target_link_libraries(mylib PRIVATE
    Qt${QT_VERSION_MAJOR}::Core)


target_link_libraries(TestAdd PRIVATE
    mylib
    Qt${QT_VERSION_MAJOR}::Gui
    Qt${QT_VERSION_MAJOR}::Test)

Adding two target_link_libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM