在C变量的声明和定义之间的混淆 [英] Confusion between declaration and definition of a variable in C

查看:188
本文介绍了在C变量的声明和定义之间的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C和我经历了变量的声明和定义之间有一些混乱。我想知道的另一件事情是,如果满足以下条件:

I am new to C and I experience some confusion between the declaration and definition of a variable. Another thing I would like to know is if the following is true:

宣言多次出现和定义来一次。​​

"Declaration appears many times and definition comes once."

还有:

int x; 

这是唯一的声明?由于内存分配给 X 那么为什么不是这样的定义,而不是一个声明?

Is this a declaration only? Since memory is allocated for x then why isn't this a definition instead of a declaration?

推荐答案

这是你看不到太多的用C的东西,但它的工作原理是这样的:

This isn't something you see too much in C, but it works like this:

在一个头文件,你可以有这样一行:

In a header file, you can have a line like this:

extern int x; //declaration

由于该的extern 修改的,这告诉编译器存在名为一个int点¯x的地方的。编译器不会为它分配空间 - 它只是增加了 INT X 来的,你可以使用的变量列表。这将只分配给空间X 时,看到这样一行:

Because of the extern modifier, this tells the compiler that there is an int named x somewhere. The compiler doesn't allocate space for it - it just adds int x to the list of variables you can use. It'll only allocate space for x when it sees a line like this:

int x; //definition

您可以看到,因为只有 INT X; 行改变了你的可执行文件,你可以有很多的的extern INT X; 行你觉得喜欢。只要有只有 INT X; 行,一切都将工作像你想让它 - 有多次声明不会改变任何事情。

You can see that because only the int x; line changes your executable, you can have as many extern int x; lines as you feel like. As long as there's only int x; line, everything will work like you want it to - having multiple declarations doesn't change a thing.

有一个更好的例子来自C ++(对不起,如果这是唯一的C-的问题 - 这适用于结构取值为好,但我不知道语法关我的头顶部):

A better example comes from C++ (sorry if this is a C-only question - this applies to structs as well, but I don't know the syntax off the top of my head):

class Pineapple; //declaration

Pineapple* ptr;  //this works
Pineapple pine;  //this DOES NOT work

此的声明的告诉编译器,有一个叫菠萝级。它并没有告诉我们关于类(它有多大,哪些成员是)什么。我们可以用指针菠萝了,但我们还不能有实例 - 我们不知道是什么让一个菠萝,所以我们不知道一个实例多少空间占用

This declaration tells the compiler that there's a class called "Pineapple". It doesn't tell us anything about the class (how big it is, what its members are). We can use pointers to Pineapples now, but we can't yet have instances - we don't know what makes up a Pineapple, so we don't know how much space an instance takes up.

class Pineapple
{
public:
    int ounces;
    char* name;
}; //definition

Pineapple* ptr;   //still works
Pineapple pine;   //this works now too!
//we can even get at member variables, 'cause we know what they are now:
pine.ounces = 17;

后的定义的,我们知道在课堂上的一切,所以我们可以有实例了。而象C例如,你可以有多个声明,但只能有一个定义。

After a definition, we know everything about the class, so we can have instances, too. And like the C example, you can have multiple declarations, but only one definition.

希望这有助于!

这篇关于在C变量的声明和定义之间的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆