Qt 4.8, CPP : mutiple definiation



  • hi everyone,

    I am having multiple defination err in my qt desktop application (qt 4.8.6 + ubuntu 12.04).

    below is my demo code.

    // global.h
    #ifndef GLOBAL_H
    #define GLOBAL_H
    
    #include <QtCore>
    #include <QObject>
    #include <QDebug>
    QString temp;
    
    #endif // GLOBAL_H
    
    
    // class1.h
    
    #ifndef CLASS1_H
    #define CLASS1_H
    
    #include <QtCore>
    #include <QObject>
    #include <QDebug>
    
    class class1: public QObject
    {
        Q_OBJECT
    public :
        Q_INVOKABLE QString class1_foo();
    };
    
    #endif // CLASS1_H
    

    // class2.h

    #ifndef CLASS2_H
    #define CLASS2_H
    
    #include <QtCore>
    #include <QObject>
    #include <QDebug>
    
    
    class class2: public QObject
    {
        Q_OBJECT
    public :
        Q_INVOKABLE QString class2_foo();
    };
    
    #endif // CLASS2_H
    

    //class1.cpp

    #include "class1.h"
    #include "class2.h"
    
    #include "global.h"
    
    QString class1::class1_foo() {
    
        qDebug() << "this is class 1";
    
    
        return "this is class 1";
    }; 
    
    // class2.cpp
    
    #include "class1.h"
    #include "class2.h"
    
    #include "global.h"
    
    QString class2::class2_foo() {
    
        class1 class1_obj;
        class1_obj.class1_foo();
    
        qDebug() << "this is class 2";
        return "this is class 2";
    } 
    

    //errors :
    /home/user/anas/qtProject/build-multiple_def_err-Desktop-Debug/class2.o:-1: In function `QFlagsQIODevice::OpenModeFlag::QFlags(QIODevice::OpenModeFlag)':

    /home/user/anas/qtProject/multiple_def_err/class2.cpp:6: multiple definition of `temp'
    /home/user/anas/qtProject/multiple_def_err/class1.cpp:7: error: first defined here

    : error: collect2: error: ld returned 1 exit status



  • @Anas_Deshmukh ,

    declare like this,
    const QString temp;



  • @Anas_Deshmukh
    Hi,
    This error is because of adding include statement of class A in class B and class B in class A.
    in class A you dont requires class B statement. remove that one, it will works fine.



  • your linker is right. You can't have the same temp defined in 2 different object files.

    the solution is change QString temp; into extern QString temp; and then create a global.cpp file in which you put

    #include "global.h"
    QString temp;
    


  • @VRonin Thanak you. your solution work fine


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.