C++Builder 全局变量

今天遇到了一个C++Builder 全局变量的问题,经过查找资料,终于解决了


 


A.CPP


#include <B.H>


ShowMessage(MainVersion);


 


 


B.H


 


AnsiString MainVersion;


 


C.CPP


#include <B.H>


MainVersion=”T-bag”;


 


这样三个文件,C.CPP 修改了 MainVersion 的值后,A.cpp显示为空,奇怪哈。


 


Google 得到:全局变量需要加:extern 关键字


于是修改为:extern AnsiString MainVersion


问题依然如故


再Google ,原来VCL 对 extern 关键字做了扩展,改为


extern PACKAGE   AnsiString MainVersion;


编译失败,


在B.CPP 中加入


AnsiString MainVersion;


问题全部解决。


 


奇怪哈,以前声明全局变量只放在.H 文件中,用extern PACKAGE   关键字还需要在.CPP中写一份,不知道其中的原因,如果哪位看官明白,请告诉小弟。


 

This entry was posted in 从初学者到电子工程师. Bookmark the permalink.

One Response to C++Builder 全局变量

  1. 王中王 says:

    呵呵。和CBUILDER没关系,和C++没关系。所谓的C++BUILDER扩展了extern更子虚乌有啊。

    说到底是C没学明白。

    把变更声明和定义搞混了。原来用得没问题,是因为头文件被引用得少。

    在头文件里定义变量,这个头文件被多处引用,相当于定义了多个变量,链接时应该有警告的。

    改了一个变量,另一个变量没变,是正常的。正确的做法是,如果单元将被多处使用,应该在CPP 中定义变量,在头文件中声明(extern关键字),在头文件中声明的目的是让其它单元知道这个变量在哪,而不是重新定义一个。

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word