1. 程式人生 > >C/C++中 pragma once的使用

C/C++中 pragma once的使用

files ofo Language ref ola 編譯速度 supported first have

在C/C++中,為了避免同一個文件被include多次,有兩種方式:一種是#ifndef方式,一種是#pragma once方式(在頭文件的最開始加入)。

#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE

// contents of the header
...

#endif // SOME_UNIQUE_NAME_HERE
#pragma once

// contents of the header
...
#ifndef的是方式是受C/C++語言標準支持。#ifndef方式依賴於宏名不能沖突。它不光可以保證同一個文件不會被包含多次,也能保證內容完全相同的兩個文件不會被不小心同時包含。缺點是如果不同頭文件中的宏名不小心”碰撞”,可能就會導致你看到頭文件明明存在,編譯器卻硬說找不到聲明的狀況。由於編譯器每次都需要打開頭文件才能判定是否有重復定義,因此在編譯大型項目時,#ifndef會使得編譯時間相對較長,因此一些編譯器逐漸開始支持#pragma once的方式。

#pragma once一般由編譯器提供保證:同一個文件不會被包含多次。這裏所說的”同一個文件”是指物理上的一個文件,而不是指內容相同的兩個文件。無法對一個頭文件中的一段代碼作#pragma once聲明,而只能針對文件。此方式不會出現宏名碰撞引發的奇怪問題,大型項目的編譯速度也因此提供了一些。缺點是如果某個頭文件有多份拷貝,此方法不能保證它們不被重復包含。在C/C++中,#pragma once是一個非標準

但是被廣泛支持的方式。

#pragma once方式產生於#ifndef之後。#ifndef方式受C/C++語言標準的支持,不受編譯器的任何限制;而#pragma once方式有些編譯器不支持(較老編譯器不支持,如GCC 3.4版本之前不支持#pragmaonce),兼容性不夠好。#ifndef可以針對一個文件中的部分代碼,而#pragma once只能針對整個文件。

#pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent. To speed up compile time more just forward declare instead of including in .h files when you can.

The use of #pragma once can reduce build times as the compiler will not open and read the file after the first #include of the file in the translation unit. This is referred to as multiple-include optimization. It has an effect similar to the #include guard idiom, which uses preprocessor macro definitions to prevent multiple inclusion of the contents of the file. This also helps to prevent violations of the one definition rule----the requirement that all templates,types, functions, and objects have no more than one definition in your code.

#pragma once is a non-standard, but widely supported, feature of C++ compilers. The concept is simple: any file containing #pragma once will only actually be included once, even if the programmer includes it multiple times.

GitHub: https://github.com/fengbingchun/Messy_Test

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!https://blog.csdn.net/jiangjunshow

C/C++中 pragma once的使用