我需要帮助访问跨 DLL/主程序的全局函数。我有一个类 Base
基础.h
#ifdef MAIN_DLL
#define DECLSPEC __declspec(dllexport)
#else
#define DECLSPEC __declspec(dllimport)
#endif
class Base {
private:
DECLSPEC static Filesystem * filesystem;
DECLSPEC static Logger * logger;
DECLSPEC static System * system;
public:
static void setFilesystem(Filesystem * filesystem_);
static void setApplication(Application * application_);
static void setLogger(Logger * logger_);
static void setSystem(System * system_);
static Filesystem * fs() { return filesystem; }
static Logger * log() { return logger; }
static System * sys() { return system; }
};
main.cpp(主程序)(这里预定义了MAIN_DLL)
Filesystem * Base::filesystem = 0;
Logger * Base::logger = 0;
System * Base::system = 0;
当我从dll访问时:
System * system = Base::sys();
if(system == 0) std::cout << "Error";
谢谢, 加西姆
最佳答案
这取决于系统,但您必须确保包含成员函数和静态成员数据定义的 DLL 中的符号正确导出符号,并且使用它们的 DLL 正确导入它们。在 Linux 下,这意味着在链接可执行文件时使用 -E
选项(如果符号在可执行文件中定义);在 Windows 下,您通常必须使用条件编译的编译器扩展,请参阅 __declspec
; Microsoft 编译器不支持标准 C++ 中的 DLL。
编辑:
这是一个适用于我的系统 (VC 2010) 的示例:
在 A.h 中:
#ifndef A_h_20111228AYCcNClDUzvxOX7ua19Fb9y5
#define A_h_20111228AYCcNClDUzvxOX7ua19Fb9y5
#include <ostream>
#ifdef DLL_A
#define A_EXPORT __declspec(dllexport)
#else
#define A_EXPORT __declspec(dllimport)
#endif
class A_EXPORT InA
{
static std::ostream* ourDest;
public:
static void setDest( std::ostream& dest );
static std::ostream* getStream() { return ourDest; }
};
#endif
在 A.cpp 中:
#include "A.h"
std::ostream* InA::ourDest = NULL;
void
InA::setDest( std::ostream& dest )
{
ourDest = &dest;
}
在 main.cpp 中:
#include <iostream>
#include "A.h"
int
main()
{
InA::setDest( std::cout );
std::cout << InA::getStream() << std::endl;
return 0;
}
编译并链接到:
cl /EHs /LDd /DDLL_A A.cpp
cl /EHs /MDd main.cpp A.lib
据我了解(我更喜欢 Unix),所有的 .cpp
成为 dll 的一部分应该在命令行中有/DDLL_A
调用编译器;其他人都不应该。在 Visual Studio 中,
这通常是通过为每个 dll 使用单独的项目来实现的,
每个可执行文件。在项目的属性中,有一个条目
配置属性→C/C++→预处理器→预处理器
定义;只需在其中添加 DLL_A
(但仅在一个项目中
生成 A.ddl
)。
关于c++ - 跨 dll 使用静态类变量/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8654327/