C/C++ 多文件编程&全局变量

  • 头文件中不进行任何定义,否则在多次包含时会出现多次定义的报错!
  • 头文件应全面地声明,否则在调用时会出现未定义的报错。

在main.cpp中使用A.cpp中定义的函数funA()

A.h

// A.h
#include <iostream>
using namespace std;

void funA();

A.cpp

// A.cpp
#include "A.h"

void funA() {
	cout << "This is funA() in A.cpp" << endl;
}

main.cpp

// main.cpp
#include "A.h"

int main() {
	funA();
	return 0;
}

输出:
This is funA() in A.cpp

注意:

  • A.h与A.cpp可以不同名(如A.h与fA.cpp,也可达到使用fA.cpp中函数的效果),但定义函数(funA())的源文件(A.cpp)必须包含声明该函数的头文件(A.h)才能定义该函数并实现其在其他源文件中的调用(即在A.cpp中include “A.h”)。
  • 若出现B.cpp与A.cpp同时include "A.h"并同时定义函数funA(),则会报错。
  • 可在多个源文件中分别定义头文件中声明的不同函数。

使用全局变量

- 数值变量(int、float、数组、…)

H.h

// H.h
#include <iostream>
using namespace std;

extern int x; // 声明变量
void funA();
void funB();

A.cpp

// A.cpp
#include "H.h"

int x; // 全局变量不能在函数内部定义

void funA() {
	cout << "This is funA() in A.cpp" << endl;
	x = 111;
}

B.cpp

// B.cpp
#include "H.h"

void funB() {
	cout << "This is funB() in B.cpp" << endl;
	cout << x << endl; 
	x = 222;
}

main.cpp

// main.cpp
#include "H.h"

int main() {
	funA();
	funB();
	cout << x <<endl;
	return 0;
}

输出:
This is funA() in A.cpp
This is funB() in B.cpp
111
222

- 结构体

(有待研究)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值