3

It gives undefined symbol error when accessing the extern variable from plugin

I have header file globals.h

#ifndef GLOBALS_H
#define GLOBALS_H
extern int globalNumber;
#endif // GLOBALS_H

which is included in both main application and plugin;

in main application mainwindow.cpp

#include "mainwindow.h"
int globalNumber=12345;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
          ui->setupUi(this);
    qDebug()<<"read variable from main app:"<<globalNumber;
          loadPlugin();/*loads plugin correctly with QPluginLoader using an interface.h containing virtual void run()=0;
and calls run() after the plugin loading;*/ 
    }

The plugin also have same globals.h

Inside plugin.cpp

#include<plugin.cpp>
void plugin::run()
{
qDebug()<<"read variable from plugin:"<<globalNumber;//if i comment this plugin get loaded without error
}

I get the application output as

read variable from main app:12345

Cannot load load library .../libplugin.so undefined symbol: globalNumber

Is there any other way to achieve this? Can it be done with singleton pattern or qglobalstatic? An example will be really helpfull. :)

  • All this idea with globalNumber looks as bad architecture, what do you really want to achieve? – demonplus Nov 03 '16 at 08:22
  • I don't think you can directly access global symbols of the main application from a run-time dynamically (after program has actually started) loaded library (such as Qt plugin)... If you want to give plugin an access, easiest is if you pass the variable (or whatever) to the plugin, basically as a pointer (or reference). – hyde Nov 03 '16 at 08:22
  • @hyde Agree, better get rid of globals.h and pass necessary values to functions – demonplus Nov 03 '16 at 08:23
  • thanks @demonplus and hyde. The idea is to store lot of general variables in globals.h that have to be used in many plugins at countless occasions. So felt passing them as boring. My plan B is to add these variables as properties of QApplication [ qApp->setProperty() ] or subclass qApplication to include these variables. That is working. Is this method a bad one? – Ramzy Valiyakath Nov 03 '16 at 09:00
  • 1
    Does `globalNumber` not have to be declared `extern "C"`? Otherwise the run time loader/linker needs to know the name mangling scheme used by the C++ compiler. – G.M. Nov 03 '16 at 09:03

0 Answers0