尽管使用了正确的dllExport-Visual Studio,但没有函数导出到DLL中

No functions get exported into DLL despite proper dllExport - Visual Studio

本文关键字:函数 DLL Studio dllExport-Visual      更新时间:2023-10-16

我有一个基类(QIndicator),我想在DLL中实现派生类。Visual Studio 2012中用于示例派生类的DLL项目具有以下代码:

具有基类的头文件

#ifndef _DLL_COMMON_INDICATOR_
#define _DLL_COMMON_INDICATOR_
// define the DLL storage specifier macro
#if defined DLL_EXPORT
    #define DECLDIR __declspec(dllexport)
#else
    #define DECLDIR __declspec(dllimport)
#endif
class QIndicator 
{
    private:
        int x;
        int y;
};
extern "C"      
{
    // declare the factory function for exporting a pointer to QIndicator
    DECLDIR QIndicator * __stdcall getIndicatorPtr(void);
}
#endif 

具有派生类的源文件

#define DLL_EXPORT
#include "indicator.h"
class QIndicatorDer : public QIndicator
{
    public:
        QIndicatorDer       (void) : QIndicator(){};
        ~QIndicatorDer      (void){};
    private:
        // list of QIndicatorDer parameters
        int x2;
        int y2;
};
extern "C"     
{
    DECLDIR QIndicator * __stdcall getIndicatorPtr(void)
    {
        return new QIndicatorDer();
    };
}

我遇到的问题是,成功构建后,生成的DLL文件不包含导出的getIndicatorPtr函数(如DependencyWalker所示)。我检查了dllexport关键字是否正确地传播到getIndicatorPtr的声明中,并且确实如此。

另一个有趣的问题是,在我几个月前创建的另一个DLL项目中,我已经有了另一个类似这样的派生类。这个老项目基本上是一样的,一切都很好。我检查了旧项目和当前项目的所有属性,它们看起来完全相同。所以我没什么想法了,为什么我不能把getIndicatorPtr导出。

非常感谢您的帮助,Daniel

这是因为它没有被导出。为什么?

__declspec说明符只能放在函数的声明中,而不能放在其定义中。此外,避免类似#define DLL_EXPORT的内容。预处理器定义应在项目属性(MSVC)或命令行选项(例如,GCC中的-D)中定义。

看看你的代码:

标题

extern "C"      
{
    DECLDIR QIndicator * __stdcall getIndicatorPtr(void);
}

编译器解析此标头时,会将DECLDIR视为dllimport(因为您在.cpp中定义了DLL_EXPORT)。然后在.cpp中,它突然出现为dllexport。使用哪一个?第一个。

所以,留下你的标题(这很好),但改变你的来源:

//#define DLL_EXPORT -> remove this!
#include "indicator.h"
class QIndicatorDer : public QIndicator
{
    //...
};
extern "C"     
{
    /* DECLDIR -> and this! */ QIndicator * __stdcall getIndicatorPtr(void)
    {
        return new QIndicatorDer();
    };
}

然后,转到项目属性(我假设您使用的是Visual Studio),然后转到C/C++->Preprocessor->Preprocessor Definitions,然后添加DLL_EXPORT=1

这应该行得通。