从DLL导出全局变量 [英] Exporting global variables from DLL
问题描述
我正在尝试从DLL中导出全局变量.
I'm trying to export a global variable from a DLL.
Foo.h
class Foo
{
public:
Foo()
{}
};
#ifdef PROJECT_EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
API const Foo foo;
Foo.cpp
#include "Foo.h"
const Foo foo;
当我编译上面的代码时,Visual Studio抱怨:
When I compile the above code, Visual Studio complains:
foo.cpp(3):错误C2370:'foo':重新定义;不同的存储类别 1> foo.h(14):请参见"foo"的声明
foo.cpp(3) : error C2370: 'foo' : redefinition; different storage class 1> foo.h(14) : see declaration of 'foo'
如果我使用:
external const Foo foo;
在Foo.h中,编译器很高兴,但是DLL不导出该符号.我已经设法导出有问题的函数,但是变量似乎不能以相同的方式工作……有什么想法吗?
in Foo.h the compiler is happy but then the DLL does not export the symbol. I've managed to export functions with problems, but variables don't seem to work the same way... Any ideas?
推荐答案
在标题中:
API extern const Foo foo;
在您的源文件中:
API const Foo foo;
如果没有extern
关键字,则C编译器会假定您要声明局部变量. (这并不在乎您是否恰好包含了头文件中的定义.)当您在源文件中实际声明变量时,还需要告诉编译器您计划导出该变量.
If you don't have the extern
keyword, your C compiler assumes you mean to declare a local variable. (It doesn't care that you happened to have included the definition from a header file.) You also need to tell the compiler that you're planning on exporting the variable when you actually declare it in your source file.
这篇关于从DLL导出全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!