声明和定义 [英] declaration and definition

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

问题描述

还是有疑惑的声明和定义在C项:
如果一个头文件是这样的:

Still confused with declaration and definition in term of C: if a header file is like:

#ifndef _BASIC_H_
#define _BASIC_H_

void test();
extern int i; //define or declare
#endif

和两个源文件在f1.c和f2.c包含这个标题,然后一个源文件需要定义变量i。

and two source file f1.c and f2.c contain this header, then one source file need to define the variable "i".

但如果头文件是这样的:

but if the header file is like:

#ifndef _BASIC_H_
#define _BASIC_H_

void test();
int i; //define or declare
#endif

和两个源文件在f1.c和f2.c,不包含定义这个报头中的变量i中的任何文件,它仍能通过,当我使用的变量。结果
被定义的变量时,我的问题是。

and two source files f1.c and f2.c, contain this header without define the variable "i" in any file, it still goes through when I use the variable.
my questions is when the variable is defined.

感谢

推荐答案

定义一个变量,当你的存储分配内存,也许它分配一个值。声明是当你指出具有特定名称和类型的变量存在,但内存已经被分配给它。

Defining a variable is when you allocate memory for the storage and maybe assign it a value. Declaring is when you state that a variable with a specific name and type exist, but memory has been allocated for it already.

使用该的extern的关键字意味着你在声明变量,但没有定义它。

The use of the extern keyword means that you are declaring the variable but not defining it.

在您的具体问题而言,你的第一个例子是声明和你的第二个答案是确定的。

In terms of your specific question, your first example is declaring and your second answer is defining.

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

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