【问题标题】:extern variable linking failure inside a static library静态库中的外部变量链接失败
【发布时间】:2012-04-05 08:18:30
【问题描述】:

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

文件丑陋的.h:

extern SomeStruct_type somestruct;

变量在另一个文件中定义(并且也使用)。我会叫它另一个ugly.c。

文件 anotherugly.c:

SomeStruct_type somestruct;

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

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

文件模板libfile.h:

#include<ugly.h>
...
void foo()
{
...
do something with somestruct
...
}

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

文件 appllibfile.h:

#include<templatelibfile.h>
...
void applfoo()
{
...
foo();
...
}

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

文件 main.cpp:

#include<appllibfile.h>
...
int main()
{
...
applfoo();
...
return 0;
}

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

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

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

文件模板libfile.h:

#include<ugly.h>
SomeStruct_type somestruct
...
void foo()
{
...
do something with somestruct;
...
}

但是我希望避免它,因为我不知道这是否是正确的做法(我不想冒险改变 UglyLib 重新定义不同实例的语义somestruct 变量)。 您是否有一些建议可以在不重新定义 somestruct extern 变量的情况下避免链接问题? 非常感谢!

【问题讨论】:

    标签: c++ c static-linking


    【解决方案1】:

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

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

    【讨论】:

    • @GuidoRanzuglia:您应该通过单击左侧的勾号来接受答案。
    猜你喜欢
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2020-11-27
    • 2016-05-16
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多