extern,include .c .h文件区别

extern

  1. A declaration can be done any number of times but definition only once
  2. “extern” keyword can be done any number of times but definition only once.
  3. since functions are visible throughout the progrem by default. The use of extern is not needed in function decaration/definition.Its use is redundant
  4. When extern is used with a variable, it’s only decalrd not defined
  5. As an exception, when an extern variable is decalred with initialization, it is taken as the definition of the variable as well.

c 语言是允许多次定义全局变量的,所以需要用extern 区分是声明还是定义

extern int a; // decalration of global variable
int a; //define a golbal variable a
extern int a = 0; // define a golbal variable a
int a = 0; //define a golbal variable a

include .c

如果include一个.c文件,会造成重复定义,因为#include本质是替换,造成在引用的文件中定义一次,然后在当前文件中再次定义

include.h

.h文件通常保存的是declaration(不分配内存的部分),定义在c文件中定义
#include会在预编译期间直接将.h文件的内容进行替换展开。本质就是在.c文件的前边将所有声明替换对应#include语句
在.h文件中定义,大概率造成重复定义。

猜你喜欢

转载自blog.csdn.net/yzcwansui/article/details/84325026