使用 extern 的全局变量声明 [duplicate]

global variable declaration with extern [duplicate]

提问人:djfoxmccloud 提问时间:5/14/2012 最后编辑:djfoxmccloud 更新时间:5/14/2012 访问量:5626

问:

我的问题在以下上下文中:

文件1.h

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

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

文件1.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 链接器 extern unresolved-external

评论


答:

6赞 Luchian Grigore 5/14/2012 #1

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

文件 2.h

extern CGraphWnd graph_wnd_sensor1D; // declarations

文件 2.cpp

CGraphWnd graph_wnd_sensor1D; // definition

评论

0赞 djfoxmccloud 5/14/2012
使用它,它肯定会编译,但graph_wnd_sensor1D没有 file1 中设置的值.cpp
0赞 Luchian Grigore 5/14/2012
@djfoxmccloud你怎么知道的?你在输出吗?您是否有另一个同名的局部变量?你是否以某种方式重新声明它?
0赞 djfoxmccloud 5/14/2012
在 file1.h 中,我首先将其声明为 CGraphWnd graph_wnd_sensor1D;(参见 OP),然后在 file1 .cpp 中使用它并具有一个值。然后我在 file2 中调用我的函数.cpp该函数使用 graph_wnd_sensor1D,但它与文件 1 中的信息不同.cpp即使它没有在任何地方修改。因此,file2.cpp 中的定义以某种方式覆盖了此变量的值
0赞 Luchian Grigore 5/14/2012
@djfoxmccloud“file1.h 我首先将其声明为 CGraphWnd graph_wnd_sensor1D” - 不是一个声明,而是一个定义。您需要使用 .CGraphWnd graph_wnd_sensor1D;extern
0赞 djfoxmccloud 5/14/2012
@LuchianGrigore 好吧,如果我从 file1 右键单击.cpp graph_wnd_sensor1D,则在 Visual 中,show declaration 和 show definition 都指向 CGraphWnd graph_wnd_sensor1D;在 file1.h 中。我已经更新了 OP 以获取更多信息