C++头文件包含(2):cpp多次包含同一头文件,会有什么问题?头文件保护

1、目录结构:

/base      
	/main          
		main.cpp     
		CMakeLists.txt      
	/test1          
		test.h 

2、文件内容:
2.1、不加头文件保护:多次包含重定义问题

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

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

// CMakeLists.txt  
include_directories(${CMAKE_SOURCE_DIR}/test1)    

// test1/test.h 
#include <iostream>
void func()
{     
	std::cout << "in file test1/test.h" << std::endl; 
}

// 输出: 
	error: redefinition of 'void func()'   

2.1、加头文件保护:不存在问题

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

// 多次包含
int main()  
{      
	func();   
	return 0;
} 
  
// CMakeLists.txt 
include_directories(${CMAKE_SOURCE_DIR}/test1)   

// test1/test.h  
#ifndef TEST1_TEST
#define TEST1_TEST  
#include <iostream> 
void func()  
{     
	std::cout << "in file test1/test.h" << std::endl; 
}  
#endif   

// 输出:  
	in file test1/test.h   

总结:
1、实际工作中肯定会出现头文件多级嵌套包含的场景,不可避免的存在同一头文件多次包含问题,因此必须对每一个头文件加宏定义保护。
2、加入头文件保护后,cpp文件在导入.h文件时,只会导入一次,第二次直接略过,因此不存在问题。

参考资料:
1、如果C源文件包含两个同名的头文件,将会发生什么?

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值