我不明白两者的意义。
当前回答
从c++标准文档中添加定义和声明示例(来自3.1节声明和定义)
定义:
int a; // defines a
extern const int c = 1; // defines c
int f(int x) { return x+a; } // defines f and defines x
struct S { int a; int b; }; // defines S, S::a, and S::b
struct X { // defines X
int x; // defines non-static data member x
static int y; // DECLARES static data member y
X(): x(0) { } // defines a constructor of X
};
int X::y = 1; // defines X::y
enum { up, down }; // defines up and down
namespace N { int d; } // defines N and N::d
namespace N1 = N; // defines N1
X anX; // defines anX
声明:
extern int a; // declares a
extern const int c; // declares c
int f(int); // declares f
struct S; // declares S
typedef int Int; // declares Int
extern X anotherX; // declares anotherX
using N::d; // declares d
其他回答
《K&R》(第二版)中有一些非常明确的定义;这有助于把它们放在一个地方,并作为一个整体来阅读:
"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 and val, 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 an int and that val is a double 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]
在这里找到类似的答案:C语言的技术面试问题。
声明为程序提供了一个名称;定义提供程序中实体(例如类型、实例和函数)的唯一描述。声明可以在给定的作用域中重复,它在给定的作用域中引入一个名称。
声明是定义,除非:
声明声明了一个函数,但没有指定函数体, 声明包含一个extern说明符,没有初始化式或函数体, 声明是没有类定义的静态类数据成员的声明, 声明是类名定义,
定义是声明,除非:
定义定义一个静态类数据成员, Definition定义一个非内联成员函数。
这听起来很俗气,但这是我能把这些条款直接记在脑子里的最好方法:
宣言:想象托马斯·杰斐逊发表演讲……“我在此声明这个foo在这个源代码中存在!!”
定义:想象一本字典,你正在查找Foo和它的实际意思。
变量的声明是为了通知编译器以下信息:变量的名称,它持有的值的类型和初始值(如果有的话)。也就是说,声明给出了关于变量属性的详细信息。然而,变量的定义说的是变量存储在哪里。也就是说,变量的内存是在定义变量时分配的。
可执行文件的生成阶段:
(1)预处理器->(2)转换器/编译器->(3)链接器
在第二阶段(译者/编译器),我们代码中的声明语句告诉编译器,这些东西我们将在未来使用,你可以稍后找到定义,意思是:
译者确定:什么是什么?方法声明
(3)阶段(链接器)需要定义来绑定事物
链接器确定:哪里是什么?方法定义