-4

I have a variable of QStringList which has some list in Sql.cpp file but I want to use that list in Edit.cpp. How to do that??

in sql.h:

   public:
   QString path;
   static QStringList list;

in sql.cpp ->connectDB() function :

    void sql::connectDB()
{
QDir dir;
path=ui->dbpath->text();
dir.setPath(path);
 dir.setNameFilters(QStringList()<<"*.db");
list= dir.entryList();
}

When I call entryList , the list of filenames storing in list, a QStringList.

edit.cpp:

void edit::on_pushButton_clicked()
{
SecDialog s;
s.setModal(true);

qDebug()<< sql::list.at(0);


s.exec();

}

i have included sql.h file in edit.cpp file. But I am getting error " Sql.cpp: error: undefined reference to Sql::list" in both files where list is used. Hope u get my problem..

Jagan PJ
  • 9
  • 1
  • 5
  • 2
    Please provide a [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example of your problem – Simon Apr 03 '18 at 10:18
  • 4
    Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of coding randomly. Typical way, would be to declare such a variable in a header file (via the use of `extern`), define it in a single .cpp file, and include such header wherever you want to use that variable. – Algirdas Preidžius Apr 03 '18 at 10:19
  • `extern` is not good if QStringList is filled and changed at runtime. Use signals and slots along with `qRegisterMetaType`. If QStringList is const data, never changed I would say `extern` can be used. – user3606329 Apr 03 '18 at 10:37
  • It changes at run time. I have declared it in public as "QStringList list;" in sql.h and used in sql.cpp directly. No problem.Then, I included sql.h file in edit.cpp and used it as " qDebug()<< Sql::list.at(0);" . But it is getting error like invalid use of non-static member. – Jagan PJ Apr 03 '18 at 10:55

1 Answers1

1

You can declare it as extern in Edit.cpp.

extern QStringList VarName;

update: seems like you need to add QStringList sql::list; definition to your sql.cpp

  • But It is getting error "missing template parameters " where the variable is getting used in SQL.cpp file – Jagan PJ Apr 03 '18 at 10:43
  • @JaganPJ do you have a `QStringList sql::list;` definition in your sql.cpp? – Edward Dankovsky Apr 05 '18 at 07:25
  • @JaganPJ it is a declaration, not a definition. Please, refer http://en.cppreference.com/w/cpp/language/static to see how to define a static class member – Edward Dankovsky Apr 05 '18 at 09:58
  • sorry.. It is declaration.By the way, It is working now after adding that declaration you have told.thank you very much for your time – Jagan PJ Apr 06 '18 at 04:34