Undefined reference to external variable



  • I declared here an extern variable:
    open.h
    @
    extern QString filename;
    @
    I defined here: open.cpp
    @
    void open::openfile()
    {
    QString filename=QFileDialog::getOpenFileName(
    0,
    QObject::tr("Open File"),
    ("C://"),
    ("BITMAP(*.bmp)")
    );
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    QByteArray ba=file.readAll();

    }
    

    @
    And i want to use here like this:
    mainwindow.cpp
    @
    ui->lineEdit->setText(filename);
    @
    But i got this error: undefined refernce to 'filename'
    What am i doing wrong?


  • Moderators

    Hi,

    in your code, filename is a local variable inside your openfile() function. For it to be an extern variable, you need to define it outside all functions:

    @
    QString filename;

    void open::openfile()
    {
    filename = ...
    @

    However, consider redesigning your program. Minimize your use extern/global variables to make your code more maintainable -- make filename a member variable of an object instead.


Log in to reply
 

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