C++ #pragma once

转自:https://www.cnblogs.com/hokyhu/archive/2009/03/30/1425604.html

 1.介绍

避免同一个文件被include多次,C/C++中有两种方式,一种是#ifndef方式,一种是#pragma once方式。

 #ifndef __SOMEFILE_H__
    #define __SOMEFILE_H__
    ... ... // 声明、定义语句
    #endif


 #pragma once
    ... ... // 声明、定义语句

区别:

  • #ifndef不仅可以保证同一个文件不会被包含多次,也能保证内容完全相同的两个文件(或者代码片段)不会被不小心同时包含。但如果不同头文件中宏名定义相同,那么就会有冲突,而且由于编译器每次都需要打开头文件才能判定是否有重复定义,因此在编译大型项目时,ifndef会使得编译时间相对较长。
  •   #pragma once一般由编译器提供保证:同一个文件不会被包含多次。但不保证内容是否完全一致,它只针对文件。如果某个头文件有多份拷贝,本方法不能保证他们不被重复包含。#pragma once does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files.  https://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard

 

posted @ 2022-10-25 23:26  lypbendlf  阅读(466)  评论(0编辑  收藏  举报