1
votes

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();
}
3
what does not work?Hayt
sry, i already posted error messages, it says: Reference to unresolved external symbolDušan Tichý
are you sure the test.cpp file gets compiled?Hayt
Probably you should rebuild your code. Please run qmake and clean the project before rebuild it,mohabouje

3 Answers

2
votes

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
1
votes

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.

0
votes

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.