【问题标题】:global variable declaration with extern [duplicate]使用 extern 声明全局变量 [重复]
【发布时间】:2012-05-14 14:33:32
【问题描述】:

我的问题是在以下情况下:

file1.h

#include "graphwnd.h"
#include "file2.h"

class XXX: 
{
....various things....
protected:
CGraphWnd graph_wnd_sensor1D;
}  

file1.cpp

#include "file1.h"
(... various stuff ...)

void main(){
OnInitGraph(&graph_wnd_1_sensor2D, rect_1_sensor2D);
graph_wnd_sensor1D.ShowWindow(SW_HIDE);
myYYY.Init();
}
(... various stuff ...)

这里 graph_wnd_sensor1D 有一个值并且 ShowWindow 工作

文件 2.h

extern CGraphWnd graph_wnd_sensor1D;
class YYY: 
{
void YYY::Init(){
graph_wnd_sensor1D.ShowWindow(SW_SHOW);
}
....various things....
}

这里,在 init 中,应用程序崩溃了,因为 graph_wnd_sensor1D 的信息与前一个不同。

在文件 2.cpp 中,我想使用 graph_wnd_sensor1D。但视觉产量

CMyTabCtrl.obj : error LNK2001: external symbol unresolved "class CGraphWnd graph_wnd_sensor1D"
  • 所以我们的想法是让 graph_wnd_sensor1D 成为一个在 file1 中声明的全局变量! 我怎么能解决这个问题? *

【问题讨论】:

    标签: c++ visual-studio linker extern unresolved-external


    【解决方案1】:

    您只声明了变量,但没有定义变量。在单个实现文件中添加定义。

    文件 2.h

    extern CGraphWnd graph_wnd_sensor1D; // declarations
    

    文件 2.cpp

    CGraphWnd graph_wnd_sensor1D; // definition
    

    【讨论】:

    • 使用它当然可以编译,但 graph_wnd_sensor1D 没有 file1.cpp 中设置的值
    • @djfoxmccloud 你怎么知道的?你在输出吗?你有另一个同名的局部变量吗?您是否以某种方式重新声明它?
    • 在 file1.h 中我首先将其声明为 CGraphWnd graph_wnd_sensor1D; (请参阅 OP)然后它在 file1.cpp 中使用并具有值。然后我在使用graph_wnd_sensor1D的file2.cpp中调用我的函数,但它没有与文件1.cpp中的相同的信息,即使它没有在任何地方修改。所以 file2.cpp 中的定义以某种方式覆盖了这个变量的值
    • @djfoxmccloud "file1.h 我首先将其声明为 CGraphWnd graph_wnd_sensor1D" - CGraphWnd graph_wnd_sensor1D; 不是声明,而是定义。您需要使用extern 声明它。
    • @LuchianGrigore 如果我从 file1.cpp graph_wnd_sensor1D 右键单击​​,则显示声明和显示定义都指向 CGraphWnd graph_wnd_sensor1D;在文件 1.h 中。我已经更新了 OP 以获取更多信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2014-02-12
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多