The meaning of both eludes me.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
definition means actual function written & declaration means simple declare function for e.g.
and
this is definition of function myfunction
Declaration
Definition
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:
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:
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:
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++.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.