当你使用extern存储类时,声明和定义的概念会成为一个陷阱,因为你的定义将在其他位置,而你在本地代码文件(页面)中声明变量。C和C++之间的一个区别是,在C中,声明通常在函数或代码页的开头完成。在C++中不是这样的。你可以在任何你选择的地方进行声明。
可执行文件生成的阶段:
(1) 预处理器 -> (2) 翻译器/编译器 -> (3) 链接器
在第二阶段(翻译器/编译器)中,我们代码中的声明语句告诉编译器这些东西将来会用到,你可以稍后找到定义,意思是:
翻译器确保:什么是什么? 意味着声明
而第三阶段(链接器)需要定义来绑定这些东西
链接器确保:什么在哪里? 意味着定义
我最喜欢的例子是 "int Num = 5",在这里你的变量被定义为1. int类型,2. 命名为Num,3. 并赋值为五。我们
类或结构体允许您在稍后使用时更改对象的定义方式。例如
当我们学习编程时,这两个术语经常混淆,因为我们经常同时进行这两种操作。
变量的声明是为了向编译器提供以下信息:变量的名称、它所持有的值的类型以及初始值(如果有)。也就是说,声明提供了关于变量属性的详细信息。而变量的定义则说明了变量存储的位置。也就是说,在变量定义期间分配了变量的内存。
声明是指创建原始类型或对象引用变量或方法时,未分配值或对象。 int a; final int a;
定义意味着分别分配值或对象 int a =10;
初始化意味着为相应的变量或对象分配内存。
"Definition" refers to the place where the variable is created or assigned storage; "declaration" refers to the places where the nature of the variable is stated but no storage is allocated. [p. 33]
...
It is important to distinguish between the declaration of an external variable and its definition. A declaration announces the properties of a variable (primarily its type); a definition also causes storage to be set aside. If the lines
int sp; double val[MAXVAL]
appear outside of any function, they define the external variables
sp
andval
, cause storage to be set aside, and also serve as the declaration for the rest of that source file.On the other hand, the lines
extern int sp; extern double val[];
declare for the rest of the source file that
sp
is anint
and thatval
is adouble
array (whose size is determined elsewhere), but they do not create the variables or reserve storage for them.There must be only one definition of an external variable among all the files that make up the source program. ... Array sizes must be specified with the definition, but are optional with an
extern
declaration. [pp. 80-81]...
Declarations specify the interpretation given to each identifier; they do not necessarily reserve storage associated with the identifier. Declarations that reserve storage are called definitions. [p. 210]
声明是指为变量(在变量声明的情况下)命名和确定类型,例如:
int i;
或者在函数声明时只给出函数名、返回类型和参数类型,而不给出函数体,例如:
int max(int, int);
而定义则意味着给变量赋值(在变量定义的情况下),例如:
i = 20;
int max(int a, int b)
{
if(a>b) return a;
return b;
}
很多时候声明和定义可以一起完成,例如:
int i=20;
并且:
int max(int a, int b)
{
if(a>b) return a;
return b;
}
max()
。