Important: Please read the Qt Code of Conduct -

Passing Data From QT To C++

  • I was working through one of the examples on signals and slots and ive found that there is one line of code that is causing compilation issues. Here is my code

    @#include <iostream>
    #include <QObject>
    using namespace std;

    class Counter : public QObject{
    void valueChanged(int newValue);
    m_value = 1;
    int value() const {
    return m_value;
    public slots:
    void setValue(int value);
    int m_value;

    void Counter::setValue(int value){
    if(value != m_value){
    m_value = value;
    emit valueChanged(value); // This line is causing errors

    int main(void){
    Counter a, b;
    QObject :: connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int)));

    cout << "a.setValue(7) " << endl;
    cout << "(a.value, b.value) = " << a.value() << b.value() << endl;
    return 0;


    Particularly, the error its causing is

    john:~/Desktop/QT/gui1$ make
    g++ -m64 -Wl,-O1 -o gui1 example1.o -L/usr/X11R6/lib64 -lQt5Gui -L/usr/lib/x86_64-linux-gnu -lQt5Core -lGL -lpthread
    example1.o: In function Counter::setValue(int)': example1.cpp:(.text+0x9): undefined reference toCounter::valueChanged(int)'
    collect2: error: ld returned 1 exit status
    make: *** [gui1] Error 1

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    since you declared your QObject class in main.cpp moc is not run. Just move it to it's own header and you should be good to go

  • Hi,
    thanks for the quick response, that was indeed the issue!

  • SGaist - you can declare QObject derived classes in main.cpp, after your class throw in @#include "main.moc"@

    So it seems the problem is not about the moc not running.

Log in to reply