C++定义全局变量的方法

2023年6月26日12:08:16

我们想定义一个全局变量,能够在多个文件中使用

//hello.h

#ifndef HELLO_H_
#define HELLO_H_
extern int a;
void fun ();
#endif
//hello.c

#include <stdio.h>
#include "hello.h"
int a = 0;
void fun () {
	a = 1;
	printf("%d\n",a);
}

//main.c



#include <stdio.h>
#include "hello.h"
int main () {
	fun();
	a = 10;
	printf("%d\n",a);
	return 0;
}

输出结果为1,10;
extern关键字来声明变量为外部变量,而为什么要在hello.h文件中已经extern int a了还要再在hello.c文件中定义int a呢?

这是因为extern仅仅是作为一个声明,声明我要定义一个外部全局变量a可以在其他文件和模块中使用,但此时并为给a分配空间。
而int a = 0;则才是真正对a的定义,为其分配空间。
那么问题又来了,我们为什么不写成extern int a = 0;的形式不是更简单吗?

这就涉及到c的一个基本知识点了也就是extern int a = 0和int a = 0同样都是对a的定义,只不过第二种是省略了extern而已。

  • 作者:寰宇C++
  • 原文链接:https://salman.blog.csdn.net/article/details/100578880
    更新时间:2023年6月26日12:08:16 ,共 532 字。