全局变量的未解析外部符号 [英] Unresolved external symbol for global variable

查看:86
本文介绍了全局变量的未解析外部符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力理解这个问题,希望有人能给我一些提示.我有一个使用漂亮的计数器习惯用法定义的全局变量.

I've been struggling to understand this issue, hope someone can give me some hints. I have a global variable defined using the nifty counter idiom.

在头文件中,定义如下:

In the header file the definition looks like:

BOOST_SYMBOL_EXPORT extern MyClass& GVar;

在源文件中,我有以下内容:

In the source file I have the following:

MyClass& GVar = reinterpret_cast<MyClass&>(Buffer);

在Debian和Ubuntu上使用GCC可以正确编译和链接所有内容.但是,在Windows上,尝试将DLL链接到测试可执行文件时出现以下错误:

Using GCC on Debian and Ubuntu everything is compiled and linked correctly. On Windows, though, I get the following error when trying to link the DLL to my test executable:

error LNK2001: unresolved external symbol "class MyClass& GVar" (GVAR_MANGLED_NAME)

我还检查了DLL中是否存在该符号,并且该符号似乎已存在于导出的符号中.我真的不知道还能尝试什么.

I also checked that the symbol exists in the DLL and it seems to be there, among the exported ones. I don't really know what else to try anymore.

有人有类似这样的问题的经验吗?

Does anyone have any experience with a problem like this?

推荐答案

因此,此问题是由于此原因引起的(来自

So the issue was due to this (from here):

__ declspec(dllimport)可以在代码和数据上使用,并且它们的语义在两者之间略有不同.当应用于例行调用时,它纯粹是一种性能优化.对于数据,它是正确性所必需的.[...]如果从DLL导出数据项,则必须在访问它的代码中使用 __ declspec(dllimport)声明它.在函数声明中,可以选择使用 __ declspec(dllimport),但是如果您使用此关键字,则编译器将生成更有效的代码.但是,对于导入的可执行文件,必须使用 __ declspec(dllimport)来访问DLL的公共数据符号和对象.

__declspec(dllimport) can be used on both code and data, and its semantics are subtly different between the two. When applied to a routine call, it is purely a performance optimization. For data, it is required for correctness. [...] If you export a data item from a DLL, you must declare it with __declspec(dllimport) in the code that accesses it. Using __declspec(dllimport) is optional on function declarations, but the compiler produces more efficient code if you use this keyword. However, you must use __declspec(dllimport) for the importing executable to access the DLL's public data symbols and objects.

长话短说,对于函数和类,dllimport是可选的,对于数据(例如,全局变量),它是必需的

Long story short, for functions and classes dllimport is optional, for data, for example global variables, it is mandatory

这篇关于全局变量的未解析外部符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆