sharing static variable between functions



  • I'm trying to use a static variable so I can call it and use it 2 different functions on the same file.

    //
    #ifndef TESTNET_C_H
    #define TESTNET_C_H
    
    #include <QMainWindow>
    #include <QtNetwork>
    #include <stdlib.h>
    
    namespace Ui {
    class Testnet_c;
    }
    
    class Testnet_c : public QMainWindow
    {
        Q_OBJECT
    
    public:
      static QString strImageFilenameDir;
        explicit Testnet_c(QWidget *parent = 0);
        ~Testnet_c();
    
    private slots:
    
       clicked();
    
    private:
        Ui::Testnet_c *ui;
        QTcpSocket * tcpSocket;
      };
    
    #endif // TESTNET_C
    

    On the Testnet_c. cpp file, i am trying to use

    void Testnet_c::on_pushButton_3_clicked()    
    {
       QString exefileName;
    
     QString Testnet_c::strImageFilenameDir;  '
     // QString strImageFilenameDir;
    QString Testnet_c::strImageFilenameDir;
    strImageFilenameDir=txtfilenameinfo.absolutePath();
    
    }
    
    void Testnet_c::on_pushButton_4_clicked()    
    {
    
     strImageFilenameDir = "Some path name"
    }
    
    

    On Testnet_c button.cpp strImageFilenameDir get path on the pushButton_3 , it should be used on another function in the same file.
    Now, i'm getting error
    qualified-id in declaration before ';' token

    If did not declare the variable on header file, use it only in the .cpp file as static, getting the correct value for first function pushButton_3 and get " " for the pushButton _4 .
    i.e it does not retain value of the path (which it got on the earlier function)

    Am i missing something? Thanks a lot..

    Cheers!
    chandra


  • Moderators

    @Chandras002 said in sharing static variable between functions:

    QString Testnet_c::strImageFilenameDir;

    Move this to Testnet_c. cpp file. You do NOT define static variables inside functions!

    QString Testnet_c::strImageFilenameDir;
    
    void Testnet_c::on_pushButton_3_clicked()    
    {
    ...
    }
    

    See https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm



  • yes. it works. Thanks a lot. It made my Day :)

    similar to my problem here to discussed,. Just for someone's reference
    https://stackoverflow.com/questions/22566322/undefined-reference-to-statically-declared-variable-in-qt

    Cheers!
    chandra


Log in to reply
 

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