Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 声明和定义_C - Fatal编程技术网

C 声明和定义

C 声明和定义,c,C,仍然与C的声明和定义混淆: 如果头文件类似于: #ifndef _BASIC_H_ #define _BASIC_H_ void test(); extern int i; //define or declare #endif #ifndef _BASIC_H_ #define _BASIC_H_ void test(); int i; //define or declare #endif 两个源文件f1.c和f2.c包含这个头,那么一个源文件需要定义变量“i” 但如果头文件如下所示:

仍然与C的声明和定义混淆: 如果头文件类似于:

#ifndef _BASIC_H_
#define _BASIC_H_

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

void test();
int i; //define or declare
#endif
两个源文件f1.c和f2.c包含这个头,那么一个源文件需要定义变量“i”

但如果头文件如下所示:

#ifndef _BASIC_H_
#define _BASIC_H_

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

void test();
int i; //define or declare
#endif
以及两个源文件f1.c和f2.c,包含此头文件,但没有在任何文件中定义变量“i”,在我使用变量时仍会执行此操作。
我的问题是何时定义变量


谢谢

定义变量是指为存储分配内存并可能为其赋值。声明是当您声明存在具有特定名称和类型的变量,但已经为其分配了内存时

使用
extern
关键字意味着您正在声明变量,但没有定义它


关于你的具体问题,你的第一个例子是声明,而第二个答案是定义。

C和C++之间有区别,但是对于你所要求的,它们不适用。注意<代码>空洞测试();代码>与
无效测试(void)不同。第二个将捕获调用
test(foo)的错误inti'给出了变量的定义。对C标准的严格解读是,如果不止一个文件包含该头文件,那么您将获得
i
的多个定义,编译的链接阶段将失败。附录J(§J.5.11)给出了一个“通用扩展”:一个对象的标识符可能有多个外部定义,无论是否明确使用关键字
extern
;如果定义不一致,或初始化了多个,则行为未定义(6.9.2)。第二种情况下int i的定义如何??是因为它得到了一个垃圾值;哪个是定义??