静态库内的外部变量链接失败

Gui*_*lia 5 c c++ static-linking

我必须在我的 C++ 应用程序中使用一个丑陋的 C 库。在下面的解释中我将其称为 UglyLib。我成功地将 UglyLib 编译为静态链接库。在文件ugly.h中,UglyLib使用了一个外部变量:

文件丑陋.h:

extern SomeStruct_type somestruct;
Run Code Online (Sandbox Code Playgroud)

该变量在另一个文件中定义(并且也使用)。我将其称为 anotherugly.c。

文件 anotherugly.c:

SomeStruct_type somestruct;
Run Code Online (Sandbox Code Playgroud)

我的 C++ 应用程序基于通用模板库 (TemplateLib),应用程序本身由主窗口 GUI 代码和与主窗口代码静态链接的应用程序库组成。我将这个静态链接库称为ApplicationLib。

TemplateLib 包含一个 templatelibfile.h,它使用 somestruct(UglyLib 公开的 extern 变量)导出函数 foo。

文件templatelibfile.h:

#include<ugly.h>
...
void foo()
{
...
do something with somestruct
...
}
Run Code Online (Sandbox Code Playgroud)

foo 函数由静态链接的 ApplicationLib 中包含的 appllibfile.h 使用。

文件appllibfile.h:

#include<templatelibfile.h>
...
void applfoo()
{
...
foo();
...
}
Run Code Online (Sandbox Code Playgroud)

主窗口应用程序包括 appllibfile.h

文件main.cpp:

#include<appllibfile.h>
...
int main()
{
...
applfoo();
...
return 0;
}
Run Code Online (Sandbox Code Playgroud)

在 VS2008 中,当我尝试编译主窗口应用程序时,微软链接器给了我这个错误

错误LNK2001:无法解析的外部符号“struct SomeStruct_type somestruct”(?somestruct@@3USomeStruct_type@@A)

如果我在 templatefile.ha 中添加 extern 变量的新定义,编译器将停止抱怨。

文件templatelibfile.h:

#include<ugly.h>
SomeStruct_type somestruct
...
void foo()
{
...
do something with somestruct;
...
}
Run Code Online (Sandbox Code Playgroud)

我希望避免它,因为我不知道这是否是正确的做法(我不想冒险改变 UglyLib 的语义,重新定义 somestruct 变量的不同实例)。为了避免链接问题而不重新定义 somestruct extern 变量,您有一些建议吗?多谢!

Bla*_*iev 5

这可能是因为 C++ 编译器进行了名称修改。由于anotherugly.c是 C 源代码(大概是用 C 编译器编译的),因此符号somestruct将被暴露而不会被破坏。当您使用 C++ 编译器编译其余文件时,链接器会查找不存在的损坏名称。

ugly.h我认为围绕in中的声明extern "C"可能会解决问题。