无法从C应用程序访问C++ DLL中的变量

Ian*_*ill 7 c c++ interop name-decoration

我坚持修复传统的Visual C++ 6应用程序.在我放的C++ DLL源代码中

extern "C" _declspec(dllexport) char* MyNewVariable = 0;
Run Code Online (Sandbox Code Playgroud)

这导致MyNewVariable在导出表中显示(很好地未修饰)(如dumpbin/exports blah.dll所示).但是,我无法弄清楚如何声明变量,以便我可以在C源文件中访问它.我尝试过各种各样的东西,包括

_declspec(dllimport) char* MyNewVariable;
Run Code Online (Sandbox Code Playgroud)

但这只是给我一个链接器错误:

未解析的外部符号"__declspec(dllimport)char*MyNewVariable"(__ imp_?MyNewVariable @@ 3PADA)

extern "C" _declspec(dllimport) char* MyNewVariable;
Run Code Online (Sandbox Code Playgroud)

正如Tony所建议的(以及我之前尝试过的)会产生不同的预期装饰,但仍然没有将其删除:

未解析的外部符号__imp__MyNewVariable

如何编写声明,以便可以从C应用程序访问C++ DLL变量?


答案

由botismarius和其他人确认(非常感谢所有),我需要链接DLL的.lib.为了防止名称被破坏,我需要声明它(在C源代码中)没有装饰器,这意味着我需要使用.lib文件.

bot*_*ius 5

你必须链接编译DLL后生成的lib.在项目的链接器选项中,您必须添加该.lib文件.是的,你还应该将变量声明为:

extern "C" { declspec(dllimport) char MyNewVariable; }
Run Code Online (Sandbox Code Playgroud)