Dušan Tichý
Dušan Tichý

Reputation: 518

Creating simple object in Qt 5.7 C++

I have following problem:

I want to create Object from class inside main function. Looks like it is a linker problem. Do you have any ideas, what the reaason for this error message could be?

Its error message is:

main.obj:-1: error: LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""public: __thiscall Test::Test(class QString)" (??0Test@@QAE@VQString@@@Z)" in Funktion "_main".

main.obj:-1: error: LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""public: __thiscall Test::~Test(void)" (??1Test@@QAE@XZ)" in Funktion "_main".


debug\Wth.exe:-1: error: LNK1120: 2 nicht aufgelöste Externe

I have very simple Class Test:

test.h

#ifndef TEST_H
#define TEST_H
#include <QtCore/QObject>

class Test
{
public:
    Test(QString name);
   ~Test();

private:
    QString m_name;
};

#endif // TEST_H

then the .cpp file looks like this:

test.cpp

#include "test.h"

Test::Test(QString st) : m_name(st){}
Test::~Test(){}

very basic, in main function I have:

main.cpp

#include <QCoreApplication>
#include "test.h"


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Test t("lam");
    return a.exec();
}

Upvotes: 1

Views: 6619

Answers (3)

mohabouje
mohabouje

Reputation: 4050

Propably you are looking an example about a creation of an QObject class.

Let's extend your code:

#ifndef TEST_H
#define TEST_H
#include <QtCore/QObject>

class Test : public QObject
{
  // Allways add the Q_OBJECT macro 
  Q_OBJECT
public:
    // Use a null default parent
    explicit Test(const QString& name, QObject* parent = 0);
   ~Test();

private:
    QString m_name;
};

#endif // TEST_H

In your cpp file:

#include "test.h"

Test::Test(const QString& st, QObject* parent) : QObject(parent), m_name(st {}
Test::~Test(){}

No in your main.cpp

#include <QCoreApplication>
#include "test.h"


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Test t("lam");
    return a.exec();
}

This should work. If you have link problems, make some steps:

  1. Run qmake (In your project folder use the contextual menu of the qt creator)
  2. Clean your project
  3. Rebuild it again

Upvotes: 2

Dušan Tich&#253;
Dušan Tich&#253;

Reputation: 518

So it turned out to be I had to run qmake first. What I was doing I was building and than running.

thanks everybody, just took much time. I am new with Qt.

Upvotes: 1

oMittens
oMittens

Reputation: 1

Right now you include test.h in main.cpp but nowhere does test.h reference the test.cpp implementation. So you must either include test.cpp at the bottom of test.h or include it in the compiler call.

Upvotes: 0

Related Questions