Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How should I include a class?



  • I want to include a class from one project in another project.

    I have a subdirs project that contains two sub projects, a windows qt console application and an autotest project to test the console application. My console application contains one class which I want to pull into my unit tests for testing:

    Here's the header:

    // calculator.h:
    #ifndef CALCULATOR_H
    #define CALCULATOR_H
    
    class Calculator{
    
    private:
    
    public:
        Calculator(int year);
    
        int getYear(){ return 666; }
        int getMonth();
        int getDay();
    };
    
    #endif
    

    Here's the source:

    // calculate.cpp
    #include "calculator.h"
    
    Calculator::Calculator(int year){}
    
    int Calculator::getMonth(){
        return 42;
    }
    
    int Calculator::getDay(){
        return 3333;
    }
    

    Here's how my unit test looks:

    //tst_foobar.cpp
    
    #include <QtTest>
    //#include "../Calculator/calculator.h"
    #include "../Calculator/calculator.cpp"
    
    // add necessary includes here
    
    class Foobar : public QObject
    {
        Q_OBJECT
    
    private slots:
        void test_case1();
    };
    
    void Foobar::test_case1()
    {
        Calculator myCalc(42);
    }
    
    QTEST_APPLESS_MAIN(Foobar)
    
    #include "tst_foobar.moc"
    

    My problem is when I include the other subdir's header file like this: #include "../Calculator/calculator.h" it doesn't work properly. I cannot test any of the class functions defined in calculator.cpp. I can explicity include calculate.cpp like this, #include "../Calculator/calculator.cpp" and my tests work as expected, but is this the proper way to do it?

    I've never seen .cpp files included into files like this, only the header? But if only include the header, the header doesn't include the function definitions in calculator.cpp? Should my headerfile include the .cpp file? That way I could include just the header in other files like you often see in C++. By why then does the class generated by QT Creator do things the other way around? Creates a header file and a .cpp file, and the .cpp file is the one that includes the header??

    Very new to C++ programming and a bit confused. Detailed help greatly appreciated.



  • @cheekibreeki95

    In general the header file (.h) includes all the class declarations and the corresponding .cpp file contains all the definitions. When using a Class, you should include the header file. See this How To.

    I think in your case (without the knowledge of the error), you missed to add the .cpp file in your test project.


Log in to reply