开发者

declaration and definition

开发者 https://www.devze.com 2023-01-09 05:01 出处:网络
Still confused with declaration and definition in term of C: if a header file is开发者_如何学C like:

Still confused with declaration and definition in term of C: if a header file is开发者_如何学C like:

#ifndef _BASIC_H_
#define _BASIC_H_

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

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

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.

Thanks


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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消