#include guards VS. #pragma once

本文详细探讨了C/C++预处理指令中的#include guards与#pragma once两种防重复包含的方法。介绍了它们各自的优缺点,并讨论了两者结合使用的可能性及存在的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. #include guards

#include guards是一种很常用的方法。

VC自动生成的使用MFC的文件会使用宏名类似"AFX_XXX_H__XXX__INCLUDED_"的#include guards。(VS用的是#pragma once)

优点:

●对于多个头文件,可以只包含其中一个(比如,完全相同的两个文件)

●可以针对文件中的一段代码

缺点:

●存在宏名冲突的隐患,造成不可预知的结果(比如,和第三方工具)

 

2. #pragma once

#pragma once是非标准的,但编译器普遍支持的命令。

优点:

●避免宏名冲突(name clash)

●编译速度快(但有些编译器,如GCC,对#include guards会进行优化处理。这样,#pragma once的这一优点就不是很明显了。)

●较少的代码

缺点:

●依赖于编译器对#pragma once的处理是否正确

●必须针对整个文件

 

3. 两者结合

缺点:

●无法避免宏名冲突

●无法避免不支持#pragma once的编译报错

于是没什么必要写成这样。

Rebuild started: Project: bs *** Using Compiler 'V5.06 update 7 (build 960)', folder: 'D:\k5\ARM\ARMCC\Bin' Rebuild target 'bs' assembling startup_stm32f407xx.s... compiling stm32f4xx_ll_adc.c... compiling i2c.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/i2c.c: 0 warnings, 1 error compiling stm32f4xx_hal_msp.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/stm32f4xx_hal_msp.c: 0 warnings, 1 error compiling adc.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/adc.c: 0 warnings, 1 error compiling gpio.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/gpio.c: 0 warnings, 1 error compiling dac.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/dac.c: 0 warnings, 1 error compiling usart.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/usart.c: 0 warnings, 1 error compiling main.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/main.c: 0 warnings, 1 error compiling stm32f4xx_hal_rcc_ex.c... compiling ssd1306.c... ../Core/Inc/ssd1306.h(18): warning: #1-D: last line of file ends without a newline #endif ssd1306.c(45): warning: #1-D: last line of file ends without a newline } ssd1306.c(12): warning: #177-D: function "SSD1306_WriteData" was declared but never referenced static void SSD1306_WriteData(uint8_t *data, uint16_t size) { ssd1306.c: 3 warnings, 0 errors compiling stm32f4xx_hal_adc_ex.c... compiling dma.c... ../Core/Inc/main.h(70): error: #3: #include file "../Core/Inc/main.h" includes itself #include "main.h" ../Core/Src/dma.c: 0 warnings,
最新发布
03-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值