我不明白两者的意义。
当前回答
为了理解声明和定义之间的区别,我们需要查看程序集代码:
uint8_t ui8 = 5; | movb $0x5,-0x45(%rbp)
int i = 5; | movl $0x5,-0x3c(%rbp)
uint32_t ui32 = 5; | movl $0x5,-0x38(%rbp)
uint64_t ui64 = 5; | movq $0x5,-0x10(%rbp)
double doub = 5; | movsd 0x328(%rip),%xmm0 # 0x400a20
movsd %xmm0,-0x8(%rbp)
这只是定义:
ui8 = 5; | movb $0x5,-0x45(%rbp)
i = 5; | movl $0x5,-0x3c(%rbp)
ui32 = 5; | movl $0x5,-0x38(%rbp)
ui64 = 5; | movq $0x5,-0x10(%rbp)
doub = 5; | movsd 0x328(%rip),%xmm0 # 0x400a20
movsd %xmm0,-0x8(%rbp)
正如你所看到的,没有任何变化。
声明与定义不同,因为声明提供的信息仅供编译器使用。例如uint8_t告诉编译器使用asm函数movb。
看到:
uint def; | no instructions
printf("some stuff..."); | [...] callq 0x400450 <printf@plt>
def=5; | movb $0x5,-0x45(%rbp)
声明没有等价的指令,因为它不是要执行的东西。
此外,声明告诉编译器变量的作用域。
我们可以说,声明是编译器用来确定正确使用变量的信息,以及某些内存属于某个变量多长时间。
其他回答
定义意味着实际编写的函数,声明意味着简单的声明函数 如。
void myfunction(); //this is simple declaration
and
void myfunction()
{
some statement;
}
这是函数myfunction的定义
变量的声明是为了通知编译器以下信息:变量的名称,它持有的值的类型和初始值(如果有的话)。也就是说,声明给出了关于变量属性的详细信息。然而,变量的定义说的是变量存储在哪里。也就是说,变量的内存是在定义变量时分配的。
从wiki.answers.com:
术语声明(在C语言中)意味着你告诉编译器关于类型,大小,如果是函数声明,任何变量的参数的类型和大小,或者程序中用户定义的类型或函数。在声明时,内存中不为任何变量保留空间。然而,编译器知道在这种类型的变量被创建的情况下要保留多少空间。
例如,以下是所有的声明:
extern int a;
struct _tagExample { int a; int b; };
int myFunc (int a, int b);
另一方面,定义意味着除了声明所做的所有事情之外,内存中还保留了空间。你可以说“DEFINITION = DECLARATION + SPACE RESERVATION”,下面是定义的例子:
int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;
看到答案。
《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]
经验法则:
声明告诉编译器如何解释内存中的变量数据。这是每个访问都需要的。 定义保留内存以使变量存在。这必须在第一次访问之前发生一次。