定义和声明有什么区别?

发布于 2024-08-05 01:20:19 字数 17 浏览 5 评论 0原文

我不明白两者的含义。

The meaning of both eludes me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

长发绾君心 2024-08-12 01:20:19

声明引入一个标识符并描述其类型,无论是类型、对象还是函数。编译器需要声明来接受对该标识符的引用。这些是声明:

extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations

定义实际上实例化/实现了该标识符。这是链接器需要的,以便将引用链接到这些实体。这些是与上述声明相对应的定义:

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};

可以使用定义代替声明。

您可以根据需要多次声明标识符。因此,以下内容在 C 和 C++ 中是合法的:

double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);

但是,它必须定义一次。如果您忘记定义已在某处声明和引用的内容,则链接器不知道将引用链接到什么,并抱怨缺少符号。如果您多次定义某个内容,则链接器不知道将引用链接到哪个定义,并且会抱怨重复的符号。


由于关于 C++ 中什么是类声明与类定义的争论不断出现(在对其他问题的回答和评论中),我将粘贴来自C++ 标准在这里。
在 3.1/2 时,C++03 说:

声明就是定义,除非它[...]是类名声明[...]。

3.1/3 然后给出了一些例子。其中:

[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example

总结一下: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:

extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type 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:

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};

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++:

double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);

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:

A declaration is a definition unless it [...] is a class name declaration [...].

3.1/3 then gives a few examples. Amongst them:

[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example

To sum it up: The C++ standard considers struct x; to be a declaration and struct 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.

迷路的信 2024-08-12 01:20:19

来自 C++ 标准第 3.1 节:

声明将名称引入翻译单元或重新声明先前引入的名称
声明。声明指定这些名称的解释和属性。

下一段指出(强调我的)声明是一个定义除非...

...它声明一个函数而不指定函数的主体:

void sqrt(double);  // declares sqrt

...它在类定义中声明一个静态成员:

struct X
{
    int a;         // defines a
    static int b;  // declares b
};

... 它声明一个类名:

class Y;

... 它包含 extern 关键字,没有初始化程序或函数体:

extern const int i = 0;  // defines i
extern int j;  // declares j
extern "C"
{
    void foo();  // declares foo
}

... 或者是 typedef使用 语句。

typedef long LONG_32;  // declares LONG_32
using namespace std;   // declares std

现在,了解声明和定义之间的区别很重要的一个重要原因是:一个定义规则。来自 C++ 标准第 3.2.1 节:

任何翻译单元都不得包含任何变量、函数、类类型、枚举类型或模板的多个定义。

From the C++ standard section 3.1:

A declaration introduces names into a translation unit or redeclares names introduced by previous
declarations. A declaration specifies the interpretation and attributes of these names.

The next paragraph states (emphasis mine) that a declaration is a definition unless...

... it declares a function without specifying the function’s body:

void sqrt(double);  // declares sqrt

... it declares a static member within a class definition:

struct X
{
    int a;         // defines a
    static int b;  // declares b
};

... it declares a class name:

class Y;

... it contains the extern keyword without an initializer or function body:

extern const int i = 0;  // defines i
extern int j;  // declares j
extern "C"
{
    void foo();  // declares foo
}

... or is a typedef or using statement.

typedef long LONG_32;  // declares LONG_32
using namespace std;   // declares std

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:

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

酷炫老祖宗 2024-08-12 01:20:19

声明:“在某个地方,存在一个 foo。”

定义:“……就在这里!”

Declaration: "Somewhere, there exists a foo."

Definition: "...and here it is!"

放血 2024-08-12 01:20:19

C++ 中有一些有趣的边缘情况(其中一些也在 C 中)。考虑

T t;

这可以是定义或声明,具体取决于 T 的类型:

typedef void T();
T t; // declaration of function "t"

struct X { 
  T t; // declaration of function "t".
};

typedef int T;
T t; // definition of object "t".

在 C++ 中,使用模板时,还有另一种边缘情况。

template <typename T>
struct X { 
  static int member; // declaration
};

template<typename T>
int X<T>::member; // definition

template<>
int X<bool>::member; // declaration!

最后一个声明不是定义。它是 X 静态成员的显式特化声明。它告诉编译器:“如果要实例化 X::member,那么不要实例化主模板中成员的定义,而是使用在其他地方找到的定义”。要使其成为定义,您必须提供一个初始值设定项

template<>
int X<bool>::member = 1; // definition, belongs into a .cpp file.

There are interesting edge cases in C++ (some of them in C too). Consider

T t;

That can be a definition or a declaration, depending on what type T is:

typedef void T();
T t; // declaration of function "t"

struct X { 
  T t; // declaration of function "t".
};

typedef int T;
T t; // definition of object "t".

In C++, when using templates, there is another edge case.

template <typename T>
struct X { 
  static int member; // declaration
};

template<typename T>
int X<T>::member; // definition

template<>
int X<bool>::member; // declaration!

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 instantiating X<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

template<>
int X<bool>::member = 1; // definition, belongs into a .cpp file.
你怎么这么可爱啊 2024-08-12 01:20:19

声明

声明告诉编译器
程序元素或名称存在。一个
声明引入一个或多个
名称到程序中。声明可以
在一个程序中出现多次。
因此,类、结构、
枚举类型和其他
用户定义类型可以声明为
每个编译单元。

定义

定义指定什么代码或数据
名字描述了。名字必须是
在使用之前声明。

Declaration

Declarations tell the compiler that a
program element or name exists. A
declaration introduces one or more
names into a program. Declarations can
occur more than once in a program.
Therefore, classes, structures,
enumerated types, and other
user-defined types can be declared for
each compilation unit.

Definition

Definitions specify what code or data
the name describes. A name must be
declared before it can be used.

童话里做英雄 2024-08-12 01:20:19

根据 C99 标准,6.7(5):

声明指定一组标识符的解释和属性。标识符的定义是该标识符的声明:

  • 对于一个对象,导致为该对象保留存储;
  • 对于函数,包括函数体;
  • 对于枚举常量或 typedef 名称,是(唯一)声明
    标识符。

根据 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:

  • for an object, causes storage to be reserved for that object;
  • for a function, includes the function body;
  • for an enumeration constant or typedef name, is the (only) declaration of the
    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++.

深空失忆 2024-08-12 01:20:19

来自 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; 

请参阅答案

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:

extern int a; 
struct _tagExample { int a; int b; }; 
int myFunc (int a, int b);

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:

int a; 
int b = 0; 
int myFunc (int a, int b) { return a + b; } 
struct _tagExample example; 

see Answers.

暮年 2024-08-12 01:20:19

C++11 更新

由于我没有看到与 C++11 相关的答案,这里有一个。

声明是一个定义,除非它声明了一个/n:

  • 不透明枚举 - enum X : int;
  • 模板参数 - template< 中的 T ;类型名称 T> class MyArray;
  • 参数声明 - int add(int x, int y); 中的 xy;
  • 别名声明 - using IntVector = std::vector;
  • 静态断言声明 - static_assert(sizeof(int) == 4, "Yikes!")
  • 属性声明(实现定义)
  • 为空声明 ;

通过上述列表从 C++03 继承的附加子句:

  • 函数声明 - int add(int x, int y); 中的 add >
  • extern 说明符包含声明或链接说明符 - extern int a;extern "C" { ... };
  • 类中的静态数据成员 - x class C { static int x; };
  • 类/结构声明 - struct Point;
  • typedef 声明 - typedef int Int;
  • using 声明 - using std::cout; >
  • using 指令 ​​- using namespace NS;

模板声明是一个声明。如果模板声明定义了函数、类或静态数据成员,则模板声明也是定义。

我发现区分声明和定义的标准示例有助于理解它们之间的细微差别:

// except one all these are definitions
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


// all these are declarations
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 N::d


// specific to C++11 - these are not from the standard
enum X : int;                           // declares X with int as the underlying type
using IntVector = std::vector<int>;     // declares IntVector as an alias to std::vector<int>
static_assert(X::y == 1, "Oops!");      // declares a static_assert which can render the program ill-formed or have no effect like an empty declaration, depending on the result of expr
template <class T> class C;             // declares template class C
;                                       // declares nothing

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:

  • opaque enum - enum X : int;
  • template parameter - T in template<typename T> class MyArray;
  • parameter declaration - x and y in int add(int x, int y);
  • alias declaration - using IntVector = std::vector<int>;
  • static assert declaration - static_assert(sizeof(int) == 4, "Yikes!")
  • attribute declaration (implementation-defined)
  • empty declaration ;

Additional clauses inherited from C++03 by the above list:

  • function declaration - add in int add(int x, int y);
  • extern specifier containing declaration or a linkage specifier - extern int a; or extern "C" { ... };
  • static data member in a class - x in class C { static int x; };
  • class/struct declaration - struct Point;
  • typedef declaration - typedef int Int;
  • using declaration - using std::cout;
  • using directive - 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:

// except one all these are definitions
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


// all these are declarations
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 N::d


// specific to C++11 - these are not from the standard
enum X : int;                           // declares X with int as the underlying type
using IntVector = std::vector<int>;     // declares IntVector as an alias to std::vector<int>
static_assert(X::y == 1, "Oops!");      // declares a static_assert which can render the program ill-formed or have no effect like an empty declaration, depending on the result of expr
template <class T> class C;             // declares template class C
;                                       // declares nothing
始于初秋 2024-08-12 01:20:19

定义:

extern int a;      // Declaration 
int a;             // Definition
a = 10             // Initialization
int b = 10;        // Definition & Initialization

定义将变量与类型相关联并分配内存,而声明仅指定类型但不分配内存。当您想在定义之前引用变量时,声明更有用。

*不要将定义与初始化混淆。两者不同,初始化赋予变量值。请参阅上面的示例。

以下是一些定义示例。

int a;
float b;
double c;

现在函数声明:

int fun(int a,int b); 

请注意函数末尾的分号,因此它表示它只是一个声明。编译器知道程序中的某个位置将使用该原型定义该函数。现在,如果编译器收到类似这样的函数调用,

int b=fun(x,y,z);

编译器将抛出一个错误,指出不存在这样的函数。因为它没有该函数的任何原型。

请注意两个程序之间的差异。

程序1

#include <stdio.h>
void print(int a)
{
     printf("%d",a);
}
main()
{
    print(5);
}

在此,还声明并定义了打印函数。由于函数调用是在定义之后进行的。现在看下一个节目。

程序2

 #include <stdio.h>
 void print(int a); // In this case this is essential
 main()
 {
    print(5);
 }
 void print(int a)
 {
     printf("%d",a);
 }

这是必不可少的,因为函数调用先于定义,所以编译器必须知道是否存在这样的函数。所以我们声明了一个通知编译器的函数。

定义:

定义函数的这部分称为定义。它说明了函数内部要做什么。

void print(int a)
{
    printf("%d",a);
}

Definition :

extern int a;      // Declaration 
int a;             // Definition
a = 10             // Initialization
int b = 10;        // Definition & Initialization

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.

int a;
float b;
double c;

Now function declaration :

int fun(int a,int b); 

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

int b=fun(x,y,z);

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

#include <stdio.h>
void print(int a)
{
     printf("%d",a);
}
main()
{
    print(5);
}

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

 #include <stdio.h>
 void print(int a); // In this case this is essential
 main()
 {
    print(5);
 }
 void print(int a)
 {
     printf("%d",a);
 }

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.

void print(int a)
{
    printf("%d",a);
}
一直在等你来 2024-08-12 01:20:19

为了理解名词,我们首先关注动词。

声明 -
正式宣布;声明

定义 -
清晰完整地展示或描述(某人或某物)

因此,当您声明某物时,您只需告诉它是什么

// declaration
int sum(int, int);

这一行声明一个名为sum的C函数,它接受两个int类型的参数并返回一个int。但是,您还不能使用它。

当您提供它实际如何工作时,这就是它的定义。

// definition
int sum(int x, int y)
{
    return x + y;
}

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.

// declaration
int sum(int, int);

This line declares a C function called sum that takes two arguments of type int and returns an int. However, you can't use it yet.

When you provide how it actually works, that's the definition of it.

// definition
int sum(int x, int y)
{
    return x + y;
}
ま昔日黯然 2024-08-12 01:20:19

定义意味着实际编写的函数&声明意味着简单声明函数
例如

void  myfunction(); //this is simple declaration

void myfunction()
{
 some statement;    
}

这是函数 myfunction 的定义

definition means actual function written & declaration means simple declare function
for e.g.

void  myfunction(); //this is simple declaration

and

void myfunction()
{
 some statement;    
}

this is definition of function myfunction

水波映月 2024-08-12 01:20:19

经验法则:

  • 声明告诉编译器如何解释内存中变量的数据。每次访问都需要这样做。

  • 定义保留内存以使变量存在。这必须在第一次访问之前发生一次。

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.

等数载,海棠开 2024-08-12 01:20:19

在这里找到类似的答案:C 语言技术面试问题。

声明为程序提供了一个名称; 定义提供程序内实体(例如类型、实例和函数)的唯一描述。声明可以在给定范围内重复,它在给定范围内引入一个名称。

声明是定义,除非:

  • 声明声明一个函数而不指定其主体,
  • 声明包含 extern 说明符并且没有初始化程序或函数主体,
  • 声明是没有类定义的静态类数据成员的声明,
  • 声明是类名定义,

定义是声明,除非:

  • 定义定义静态类数据成员,
  • 定义定义非内联成员函数。

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:

  • Declaration declares a function without specifying its body,
  • Declaration contains an extern specifier and no initializer or function body,
  • Declaration is the declaration of a static class data member without a class definition,
  • Declaration is a class name definition,

A definition is a declaration unless:

  • Definition defines a static class data member,
  • Definition defines a non-inline member function.
仙女山的月亮 2024-08-12 01:20:19

要理解声明和定义之间的区别,我们需要查看汇编代码:

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)

声明没有等效的指令,因为它没有要执行的内容。

此外,声明告诉编译器变量的范围。

我们可以说声明是编译器用来确定变量的正确使用以及某些内存属于某个变量的时间的信息。

To understand the difference between declaration and definition we need to see the assembly code:

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)

and this is only definition:

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)

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:

uint def;                  |  no instructions
printf("some stuff...");   |  [...] callq   0x400450 <printf@plt>
def=5;                     |  movb    $0x5,-0x45(%rbp)

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.

眸中客 2024-08-12 01:20:19

声明说“这个东西存在于某处”

int sampleFunc(); // function
extern int car;  // variable

定义说“这个东西存在于此;为它创建内存”

int sampleFunc() {} // function
int car; // variable

初始化在定义时是可选的对于对象,并说“这是这个东西的初始值”:

int car = 0; // variable

Declaration says "this thing exists somewhere"

int sampleFunc(); // function
extern int car;  // variable

Definition says "this thing exists here; make memory for it"

int sampleFunc() {} // function
int car; // variable

Initialization is optional at the point of definition for objects, and says "here is the initial value for this thing":

int car = 0; // variable
遗心遗梦遗幸福 2024-08-12 01:20:19

您能否用最通用的术语来说明,声明是一个没有分配存储空间的标识符,而定义实际上是从声明的标识符分配存储空间?

一个有趣的想法 - 在类或函数与类型信息链接之前,模板无法分配存储。那么模板标识符是声明还是定义呢?它应该是一个声明,因为没有分配存储空间,并且您只是对模板类或函数进行“原型设计”。

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.

萤火眠眠 2024-08-12 01:20:19

声明向编译器提供符号名称。定义是为符号分配空间的声明。

int f(int x); // function declaration (I know f exists)

int f(int x) { return 2*x; } // declaration and definition

A declaration presents a symbol name to the compiler. A definition is a declaration that allocates space for the symbol.

int f(int x); // function declaration (I know f exists)

int f(int x) { return 2*x; } // declaration and definition
美人迟暮 2024-08-12 01:20:19

这听起来确实很俗气,但这是我能够在脑海中清晰地记住这些术语的最佳方式:

声明:图片托马斯·杰斐逊发表演讲......“我特此声明此 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.

゛时过境迁 2024-08-12 01:20:19

根据 GNU C 库手册 (http://www. gnu.org/software/libc/manual/html_node/Header-Files.html

在 C 中,声明仅提供函数或变量存在的信息并给出其类型。对于函数声明,还可以提供有关其参数类型的信息。声明的目的是允许编译器正确处理对声明的变量和函数的引用。另一方面,定义实际上为变量分配存储空间或说明函数的作用。

According to the GNU C library manual (http://www.gnu.org/software/libc/manual/html_node/Header-Files.html)

In C, a declaration merely provides information that a function or variable exists and gives its type. For a function declaration, information about the types of its arguments might be provided as well. The purpose of declarations is to allow the compiler to correctly process references to the declared variables and functions. A definition, on the other hand, actually allocates storage for a variable or says what a function does.

铃予 2024-08-12 01:20:19

添加来自 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

Adding definition and declaration examples from the C++ standard document(from the section 3.1 Declarations and definitions)

Definitions:

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

Declarations:

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
2024-08-12 01:20:19

当您使用 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.

初心未许 2024-08-12 01:20:19

我最喜欢的例子是“int Num = 5”,这里你的变量是 1. 定义为 int 2. 声明为 Num 和 3. 用值 5 实例化。我们

  • 定义对象的类型,它可以是内置的,也可以是类或结构。
  • 声明对象的名称,因此已声明任何具有名称的内容,包括变量、函数等。

类或结构允许您更改稍后使用对象时的定义方式。例如,

  • 可以声明未具体定义的异构变量或数组。
  • 在 C++ 中使用偏移量,您可以定义一个没有声明名称的对象。

当我们学习编程时,这两个术语经常会混淆,因为我们经常同时进行这两个术语。

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

  • Define the type of an object, which may be built-in or a class or struct.
  • Declare the name of an object, so anything with a name has been declared which includes Variables, Funtions, etc.

A class or struct allows you to change how objects will be defined when it is later used. For example

  • One may declare a heterogeneous variable or array which are not specifically defined.
  • Using an offset in C++ you may define an object which does not have a declared name.

When we learn programming these two terms are often confused because we often do both at the same time.

蝶…霜飞 2024-08-12 01:20:19

可执行文件生成的阶段:

(1) 预处理器-> (2) 翻译器/编译器-> (3)链接器

在第 2 阶段(翻译器/编译器),我们代码中的声明语句告诉编译器我们将来要使用这些东西,稍后您可以找到定义,含义是:

翻译人员确保:什么是什么?表示声明

,并且 (3) 阶段(链接器)需要定义来绑定事物

链接器确保:什么在哪里?表示定义

Stages of an executable generation:

(1) pre-processor -> (2) translator/compiler -> (3) linker

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 :

translator make sure that : what is what ? means declaration

and (3) stage (linker) needs definition to bind the things

Linker make sure that : where is what ? means definition

蓝眼泪 2024-08-12 01:20:19

K&R(第二版)中散布着一些非常明确的定义;将它们放在一处并将它们作为一个整体阅读会有所帮助:

“定义”是指变量创建或分配存储的地方; “声明”是指声明变量性质但不分配存储空间的地方。 [页。 33]

...

区分外部变量的声明及其定义非常重要。声明宣布变量的属性(主要是其类型);定义也会导致存储被搁置。
如果行

int sp;
双值[MAXVAL]

出现在任何函数之外,它们定义外部变量spval,导致存储被预留,并且还充当该源文件其余部分的声明。

另一方面,线条

extern int sp;
外部双值[];

声明源文件的其余部分 spint 并且 val 是 < code>double 数组(其大小在其他地方确定),但它们不会创建变量或为其保留存储空间。

构成源程序的所有文件中必须只有一个外部变量的定义。 ...数组大小必须在定义中指定,但可以通过 extern 声明来指定。 [页。 80-81]

...

声明指定对每个标识符的解释;它们不一定保留与标识符相关的存储。保留存储的声明称为定义。 [页。 210]

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:

"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]

半葬歌 2024-08-12 01:20:19

声明是在创建基元或对象引用变量或方法而不分配值或对象时进行的。
整数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.

我不会写诗 2024-08-12 01:20:19

变量的声明用于告知编译器以下信息:变量的名称、变量所保存的值的类型以及初始值(如果有)。即,声明提供了有关变量属性的详细信息。而变量的定义表示变量的存储位置。即,变量的内存是在变量定义期间分配的。

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.

瑾兮 2024-08-12 01:20:19

声明意味着为变量提供名称和类型(在变量声明的情况下),例如:

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;    
} 

在上面的情况下,我们定义并声明变量i函数max()

Declaration means give name and type to a variable (in case of variable declaration), eg:

int i;

or give name,return type and parameter(s) type to a function without body(in case of function declaration), eg:

int max(int, int);

whereas definition means assign value to a variable (in case of variable definition), eg:

i = 20;

or provide/add body(functionality) to a function is called function definition, eg:

int max(int a, int b)
{
   if(a>b)   return a;
   return b;  
}

many time declaration and definition can be done together as:

int i=20;

and:

int max(int a, int b)
{
    if(a>b)   return a;
    return b;    
} 

In above cases we define and declare variable i and function max().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文