定义和声明有什么区别?
我不明白两者的含义。
The meaning of both eludes me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我不明白两者的含义。
The meaning of both eludes me.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(27)
声明引入一个标识符并描述其类型,无论是类型、对象还是函数。编译器需要声明来接受对该标识符的引用。这些是声明:
定义实际上实例化/实现了该标识符。这是链接器需要的,以便将引用链接到这些实体。这些是与上述声明相对应的定义:
可以使用定义代替声明。
您可以根据需要多次声明标识符。因此,以下内容在 C 和 C++ 中是合法的:
但是,它必须定义一次。如果您忘记定义已在某处声明和引用的内容,则链接器不知道将引用链接到什么,并抱怨缺少符号。如果您多次定义某个内容,则链接器不知道将引用链接到哪个定义,并且会抱怨重复的符号。
由于关于 C++ 中什么是类声明与类定义的争论不断出现(在对其他问题的回答和评论中),我将粘贴来自C++ 标准在这里。
在 3.1/2 时,C++03 说:
3.1/3 然后给出了一些例子。其中:
总结一下:C++ 标准认为 struct x; 是一个声明,而
struct x {};
是一个定义。。 (换句话说,“前向声明”是一个用词不当,因为 C++ 中没有其他形式的类声明。)感谢 litb (Johannes Schaub) 他在他的一个答案中挖掘出了实际的章节和诗句。
A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:
A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:
A definition can be used in the place of a declaration.
An identifier can be declared as often as you want. Thus, the following is legal in C and C++:
However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.
Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:
3.1/3 then gives a few examples. Amongst them:
To sum it up: The C++ standard considers
struct x;
to be a declaration andstruct x {};
a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.
来自 C++ 标准第 3.1 节:
下一段指出(强调我的)声明是一个定义除非...
...它声明一个函数而不指定函数的主体:
...它在类定义中声明一个静态成员:
... 它声明一个类名:
... 它包含
extern
关键字,没有初始化程序或函数体:... 或者是
typedef
或使用
语句。现在,了解声明和定义之间的区别很重要的一个重要原因是:一个定义规则。来自 C++ 标准第 3.2.1 节:
From the C++ standard section 3.1:
The next paragraph states (emphasis mine) that a declaration is a definition unless...
... it declares a function without specifying the function’s body:
... it declares a static member within a class definition:
... it declares a class name:
... it contains the
extern
keyword without an initializer or function body:... or is a
typedef
orusing
statement.Now for the big reason why it's important to understand the difference between a declaration and definition: the One Definition Rule. From section 3.2.1 of the C++ standard:
声明:“在某个地方,存在一个 foo。”
定义:“……就在这里!”
Declaration: "Somewhere, there exists a foo."
Definition: "...and here it is!"
C++ 中有一些有趣的边缘情况(其中一些也在 C 中)。考虑
这可以是定义或声明,具体取决于
T
的类型:在 C++ 中,使用模板时,还有另一种边缘情况。
最后一个声明不是定义。它是
X
静态成员的显式特化声明。它告诉编译器:“如果要实例化X::member
,那么不要实例化主模板中成员的定义,而是使用在其他地方找到的定义”。要使其成为定义,您必须提供一个初始值设定项There are interesting edge cases in C++ (some of them in C too). Consider
That can be a definition or a declaration, depending on what type
T
is:In C++, when using templates, there is another edge case.
The last declaration was not a definition. It's the declaration of an explicit specialization of the static member of
X<bool>
. It tells the compiler: "If it comes to instantiatingX<bool>::member
, then don't instantiate the definition of the member from the primary template, but use the definition found elsewhere". To make it a definition, you have to supply an initializer声明
定义
Declaration
Definition
根据 C99 标准,6.7(5):
声明指定一组标识符的解释和属性。标识符的定义是该标识符的声明:
标识符。
根据 C++ 标准 3.1(2):
声明是一个定义,除非它声明一个函数而不指定函数体,它包含 extern 说明符或链接规范,并且既不包含初始化程序也不包含函数-body,它在类声明中声明静态数据成员,它是类名声明,或者是 typedef 声明、using 声明或 using 指令。
然后还有一些例子。
有趣的是(或者不是,但我对此感到有点惊讶),
typedef int myint;
是 C99 中的定义,但只是 C++ 中的声明。From the C99 standard, 6.7(5):
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
identifier.
From the C++ standard, 3.1(2):
A declaration is a definition unless it declares a function without specifying the function's body, it contains the extern specifier or a linkage-specification and neither an initializer nor a function-body, it declares a static data member in a class declaration, it is a class name declaration, or it is a typedef declaration, a using-declaration, or a using-directive.
Then there are some examples.
So interestingly (or not, but I'm slightly surprised by it),
typedef int myint;
is a definition in C99, but only a declaration in C++.来自 wiki.answers.com:
术语“声明”意味着(在 C 语言中)您正在告诉编译器有关类型、大小的信息,如果是函数声明,则告诉编译器任何变量的参数的类型和大小,或者用户定义的类型或函数。程序。在声明的情况下,内存中不会为任何变量保留空间。然而,编译器知道在创建这种类型的变量时要保留多少空间。
例如,以下是所有声明:
另一方面,定义意味着除了声明所做的所有事情之外,还在内存中保留空间。您可以说“DEFINITION = DECLARATION + SPACE RESERVATION”,以下是定义示例:
请参阅答案。
From wiki.answers.com:
The term declaration means (in C) that you are telling the compiler about type, size and in case of function declaration, type and size of its parameters of any variable, or user defined type or function in your program. No space is reserved in memory for any variable in case of declaration. However compiler knows how much space to reserve in case a variable of this type is created.
for example, following are all declarations:
Definition on the other hand means that in additions to all the things that declaration does, space is also reserved in memory. You can say "DEFINITION = DECLARATION + SPACE RESERVATION" following are examples of definition:
see Answers.
C++11 更新
由于我没有看到与 C++11 相关的答案,这里有一个。
声明是一个定义,除非它声明了一个/n:
enum X : int;
template< 中的 T ;类型名称 T> class MyArray;
int add(int x, int y); 中的 x 和 y;
using IntVector = std::vector;
static_assert(sizeof(int) == 4, "Yikes!")
;
通过上述列表从 C++03 继承的附加子句:
int add(int x, int y); 中的 add >
extern int a;
或extern "C" { ... };
class C { static int x; };
struct Point;
typedef int Int;
using std::cout;
>using namespace NS;
模板声明是一个声明。如果模板声明定义了函数、类或静态数据成员,则模板声明也是定义。
我发现区分声明和定义的标准示例有助于理解它们之间的细微差别:
C++11 Update
Since I don't see an answer pertinent to C++11 here's one.
A declaration is a definition unless it declares a/n:
enum X : int;
template<typename T> class MyArray;
int add(int x, int y);
using IntVector = std::vector<int>;
static_assert(sizeof(int) == 4, "Yikes!")
;
Additional clauses inherited from C++03 by the above list:
int add(int x, int y);
extern int a;
orextern "C" { ... };
class C { static int x; };
struct Point;
typedef int Int;
using std::cout;
using namespace NS;
A template-declaration is a declaration. A template-declaration is also a definition if its declaration defines a function, a class, or a static data member.
Examples from the standard which differentiates between declaration and definition that I found helpful in understanding the nuances between them:
定义:
定义将变量与类型相关联并分配内存,而声明仅指定类型但不分配内存。当您想在定义之前引用变量时,声明更有用。
*不要将定义与初始化混淆。两者不同,初始化赋予变量值。请参阅上面的示例。
以下是一些定义示例。
现在函数声明:
请注意函数末尾的分号,因此它表示它只是一个声明。编译器知道程序中的某个位置将使用该原型定义该函数。现在,如果编译器收到类似这样的函数调用,
编译器将抛出一个错误,指出不存在这样的函数。因为它没有该函数的任何原型。
请注意两个程序之间的差异。
程序1
在此,还声明并定义了打印函数。由于函数调用是在定义之后进行的。现在看下一个节目。
程序2
这是必不可少的,因为函数调用先于定义,所以编译器必须知道是否存在这样的函数。所以我们声明了一个通知编译器的函数。
定义:
定义函数的这部分称为定义。它说明了函数内部要做什么。
Definition :
Definition associates the variable with a type and allocates memory, whereas declaration just specifies the type but doesn't allocate memory. Declaration is more useful when you want to refer the variable before definition.
*Don't confuse definition with initialization. Both are different, initialization gives value to the variable. See the above example.
Following are some examples of definition.
Now function declaration :
Note the semicolon at the end of function so it says it is only a declaration. Compiler knows that somewhere in the program that function will be defined with that prototype. Now if the compiler gets a function call something like this
Compiler will throw an error saying that there is no such function. Because it doesn't has any prototype for that function.
Note the difference between two programs.
Program 1
In this, print function is declared and defined as well. Since function call is coming after the definition. Now see the next program.
Program 2
It is essential because function call precedes definition so compiler must know whether there is any such function. So we declare the function which will inform the compiler.
Definition :
This part of defining a function is called Definition. It says what to do inside the function.
为了理解名词,我们首先关注动词。
声明 -
正式宣布;声明
定义 -
清晰完整地展示或描述(某人或某物)
因此,当您声明某物时,您只需告诉它是什么。
这一行声明一个名为
sum
的C函数,它接受两个int
类型的参数并返回一个int
。但是,您还不能使用它。当您提供它实际如何工作时,这就是它的定义。
To understand the nouns, let's focus on the verbs first.
declare -
to announce officially; proclaim
define -
to show or describe (someone or something) clearly and completely
So, when you declare something, you just tell what it is.
This line declares a C function called
sum
that takes two arguments of typeint
and returns anint
. However, you can't use it yet.When you provide how it actually works, that's the definition of it.
定义意味着实际编写的函数&声明意味着简单声明函数
例如
,
这是函数 myfunction 的定义
definition means actual function written & declaration means simple declare function
for e.g.
and
this is definition of function myfunction
经验法则:
声明告诉编译器如何解释内存中变量的数据。每次访问都需要这样做。
定义保留内存以使变量存在。这必须在第一次访问之前发生一次。
Rule of thumb:
A declaration tells the compiler how to interpret the variable's data in memory. This is needed for every access.
A definition reserves the memory to make the variable existing. This has to happen exactly once before first access.
在这里找到类似的答案:C 语言技术面试问题。
声明为程序提供了一个名称; 定义提供程序内实体(例如类型、实例和函数)的唯一描述。声明可以在给定范围内重复,它在给定范围内引入一个名称。
声明是定义,除非:
定义是声明,除非:
Find similar answers here: Technical Interview Questions in C.
A declaration provides a name to the program; a definition provides a unique description of an entity (e.g. type, instance, and function) within the program. Declarations can be repeated in a given scope, it introduces a name in a given scope.
A declaration is a definition unless:
A definition is a declaration unless:
要理解声明和定义之间的区别,我们需要查看汇编代码:
这只是定义:
正如您所看到的,没有任何变化。
声明与定义不同,因为它提供仅供编译器使用的信息。例如uint8_t告诉编译器使用asm函数movb。
请注意:
声明没有等效的指令,因为它没有要执行的内容。
此外,声明告诉编译器变量的范围。
我们可以说声明是编译器用来确定变量的正确使用以及某些内存属于某个变量的时间的信息。
To understand the difference between declaration and definition we need to see the assembly code:
and this is only definition:
As you can see nothing change.
Declaration is different from definition because it gives information used only by the compiler. For example uint8_t tell the compiler to use asm function movb.
See that:
Declaration haven't an equivalent instruction because it is no something to be executed.
Furthermore declaration tells the compiler the scope of the variable.
We can say that declaration is an information used by the compiler to establish the correct use of the variable and for how long some memory belongs to certain variable.
声明说“这个东西存在于某处”
定义说“这个东西存在于此;为它创建内存”
初始化在定义时是可选的对于对象,并说“这是这个东西的初始值”:
Declaration says "this thing exists somewhere"
Definition says "this thing exists here; make memory for it"
Initialization is optional at the point of definition for objects, and says "here is the initial value for this thing":
您能否用最通用的术语来说明,声明是一个没有分配存储空间的标识符,而定义实际上是从声明的标识符分配存储空间?
一个有趣的想法 - 在类或函数与类型信息链接之前,模板无法分配存储。那么模板标识符是声明还是定义呢?它应该是一个声明,因为没有分配存储空间,并且您只是对模板类或函数进行“原型设计”。
Couldnt you state in the most general terms possible, that a declaration is an identifier in which no storage is allocated and a definition actually allocates storage from a declared identifier?
One interesting thought - a template cannot allocate storage until the class or function is linked with the type information. So is the template identifier a declaration or definition? It should be a declaration since no storage is allocated, and you are simply 'prototyping' the template class or function.
声明向编译器提供符号名称。定义是为符号分配空间的声明。
A declaration presents a symbol name to the compiler. A definition is a declaration that allocates space for the symbol.
这听起来确实很俗气,但这是我能够在脑海中清晰地记住这些术语的最佳方式:
声明:图片托马斯·杰斐逊发表演讲......“我特此声明此 FOO 存在于此源代码中!!!”
定义:想象一下字典,您正在查找 Foo 及其实际含义。
This is going to sound really cheesy, but it's the best way I've been able to keep the terms straight in my head:
Declaration: Picture Thomas Jefferson giving a speech... "I HEREBY DECLARE THAT THIS FOO EXISTS IN THIS SOURCE CODE!!!"
Definition: picture a dictionary, you are looking up Foo and what it actually means.
根据 GNU C 库手册 (http://www. gnu.org/software/libc/manual/html_node/Header-Files.html)
According to the GNU C library manual (http://www.gnu.org/software/libc/manual/html_node/Header-Files.html)
添加来自 C++ 标准文档的定义和声明示例(来自 3.1 声明和定义部分)
定义:
声明:
Adding definition and declaration examples from the C++ standard document(from the section 3.1 Declarations and definitions)
Definitions:
Declarations:
当您使用 extern 存储类时,声明和定义的概念将形成一个陷阱,因为您的定义将位于其他位置,并且您在本地代码文件(页面)中声明变量。 C 和 C++ 之间的一个区别是,在 C 中,声明通常在函数或代码页的开头完成。在 C++ 中,情况并非如此。您可以在您选择的地点进行申报。
The concept of Declaration and Definition will form a pitfall when you are using the extern storage class because your definition will be in some other location and you are declaring the variable in your local code file (page). One difference between C and C++ is that in C you the declarations are done normally at the beginning of a function or code page. In C++ it's not like that. You can declare at a place of your choice.
我最喜欢的例子是“int Num = 5”,这里你的变量是 1. 定义为 int 2. 声明为 Num 和 3. 用值 5 实例化。我们
类或结构允许您更改稍后使用对象时的定义方式。例如,
当我们学习编程时,这两个术语经常会混淆,因为我们经常同时进行这两个术语。
My favorite example is "int Num = 5" here your variable is 1. defined as int 2. declared as Num and 3. instantiated with a value of five. We
A class or struct allows you to change how objects will be defined when it is later used. For example
When we learn programming these two terms are often confused because we often do both at the same time.
可执行文件生成的阶段:
在第 2 阶段(翻译器/编译器),我们代码中的声明语句告诉编译器我们将来要使用这些东西,稍后您可以找到定义,含义是:
,并且 (3) 阶段(链接器)需要定义来绑定事物
Stages of an executable generation:
In stage 2 (translator/compiler), declaration statements in our code tell to the compiler that these things we are going to use in future and you can find definition later, meaning is :
and (3) stage (linker) needs definition to bind the things
K&R(第二版)中散布着一些非常明确的定义;将它们放在一处并将它们作为一个整体阅读会有所帮助:
There are some very clear definitions sprinkled throughout K&R (2nd edition); it helps to put them in one place and read them as one:
声明是在创建基元或对象引用变量或方法而不分配值或对象时进行的。
整数a;
最终整数a;
定义的意思是分别给值或者对象赋值
整数a=10;
初始化意味着为相应的变量或对象分配内存。
The declaration is when a primitive or object reference variable or method is created without assigning value or object.
int a;
final int a;
The definition means assigning the value or object respectively
int a =10;
Initialization means allocating memory for a respective variable or object.
变量的声明用于告知编译器以下信息:变量的名称、变量所保存的值的类型以及初始值(如果有)。即,声明提供了有关变量属性的详细信息。而变量的定义表示变量的存储位置。即,变量的内存是在变量定义期间分配的。
Declaration of a variable is for informing to the compiler the following information: name of the variable, type of value it holds and the initial value if any it takes. i.e., declaration gives details about the properties of a variable. Whereas, Definition of a variable says where the variable gets stored. i.e., memory for the variable is allocated during the definition of the variable.
声明意味着为变量提供名称和类型(在变量声明的情况下),例如:
或为没有主体的函数提供名称、返回类型和参数类型(在函数声明的情况下),例如:
而定义意味着分配变量的值(在变量定义的情况下),例如:
或向函数提供/添加主体(功能)称为函数定义,例如:
很多时候声明和定义可以一起完成,如:
和:
在上面的情况下,我们定义并声明变量
i
和函数max()
。Declaration means give name and type to a variable (in case of variable declaration), eg:
or give name,return type and parameter(s) type to a function without body(in case of function declaration), eg:
whereas definition means assign value to a variable (in case of variable definition), eg:
or provide/add body(functionality) to a function is called function definition, eg:
many time declaration and definition can be done together as:
and:
In above cases we define and declare variable
i
andfunction max()
.