我在delphi dll中有一些函数,我想一次加载它们(使用QtLibrary)。
我可以将这些函数存储在全局变量中以使用它吗?我试图在.h文件中声明全局函数指针并在主文件中解析它们,但得到错误“多重定义”
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qlibrary.h>
#include <QDebug>
#include "mapwidget.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString path = "map_dll.dll";
if (QLibrary::isLibrary(path)) {
lib = new QLibrary(path);
lib->load();
if (!lib->isLoaded()) {
qDebug() << lib->errorString();
} else {
nearestWell = (void( *)(double x,
double y,
double &wellX,
double &wellY))
lib->resolve("nearestWell");
}
}
}
void MainWindow :: on_pushButton_2_clicked() {
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLibrary>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QLibrary *lib;
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mapwidget.h
#ifndef MAPWIDGET_H
#define MAPWIDGET_H
#include <QWidget>
#include <QPainter>
typedef void (*NearestWellFunc) (double x, double y, double &wellX,
double &wellY);
extern NearestWellFunc nearestWell;
....
#endif // MAPWIDGET_H
错误消息:
debug/mainwindow.o: In function `ZN10MainWindow21on_pushButton_clickedEv':
C:\nipi\APT\map_qt\build-MIG-Desktop_Qt_5_1_0_MinGW_32bit-Debug/../MIG/mainwindow.cpp:33: undefined reference to `nearestWell'
C:\nipi\APT\map_qt\build-MIG-Desktop_Qt_5_1_0_MinGW_32bit-Debug/../MIG/mainwindow.cpp:40: undefined reference to `nearestWell'
C:\nipi\APT\map_qt\build-MIG-Desktop_Qt_5_1_0_MinGW_32bit-Debug/../MIG/mainwindow.cpp:54: undefined reference to `nearestWell'
Makefile.Debug:84: recipe for target 'debug/MIG.exe' failed
mingw32-make[1]: Leaving directory 'C:/nipi/APT/map_qt/build- MIG-Desktop_Qt_5_1_0_MinGW_32bit-Debug'
makefile:34: recipe for target 'debug' failed
C:\nipi\APT\map_qt\build-MIG-Desktop_Qt_5_1_0_MinGW_32bit-Debug/../MIG/mainwindow.cpp:63: undefined reference to `nearestWell'
collect2.exe: error: ld returned 1 exit status
mingw32-make[1]: *** [debug/MIG.exe] Error 1
mingw32-make: *** [debug] Error 2
答案 0 :(得分:3)
此错误:
未定义对`nearestWell'的引用
编译器是否说“我知道有一个名为nearestWell
的东西,但我不知道它存储在哪里(因为它尚未定义)”
这一行:
extern NearestWellFunc nearestWell;
说编译器“在其他地方会有一个名为NearestWellFunc
的{{1}}”。
这是一个声明 - 它告诉编译器将一个名为nearestWell
的变量。
它需要与定义配对,告诉编译器为变量留出一些空间。在这种情况下,它看起来像:
nearestWell
请记住,您只能定义一次,否则编译器会感到困惑。这就是你需要将声明放在.cpp文件而不是.h文件中的原因 - 如果你把定义放在头文件中,那么包含该头的每个.cpp文件都将包含定义,这就是导致多重定义错误。
查看您的示例结构,我将定义放在mainwindow.cpp。
中答案 1 :(得分:2)
您可以在头文件中声明变量,但不能定义它们。
例如,在头文件中将变量声明为extern
就可以了。你可能会定义它们。将extern
关键字添加到头文件中的声明中,并在源文件中添加定义。