Pragma once

In the C and C++ programming languages, #pragma once is a non-standard but widely supported preprocessor directive designed to cause the current header file to be included only once in a single compilation.[1] Thus, #pragma once serves the same purpose as #include guards, but with several advantages, including less code, avoidance of name clashes, and sometimes improvement in compilation speed.[2] While #pragma once is available in most modern compilers, its implementation is tricky and might not always be reliable.

Example

File "grandparent.h"
#pragma once

struct foo 
{
    int member;
};
File "parent.h"
#include "grandparent.h"
File "child.c"
#include "grandparent.h"
#include "parent.h"

In this example, the inclusion of grandparent.h in both parent.h and child.c would ordinarily cause a compilation error, because a struct with a given name can only be defined a single time in a given compilation. The #pragma once directive serves to avoid this by ignoring subsequent inclusions of grandparent.h.

Advantages

Using #pragma once allows the C preprocessor to include a header file when it is needed and to ignore an #include directive otherwise. This has the effect of altering the behavior of the C preprocessor itself, and allows programmers to express file dependencies in a simple fashion, obviating the need for manual management.

The most common alternative to #pragma once is to use #define to set an #include guard macro, the name of which is picked by the programmer to be unique to that file. For example,

#ifndef GRANDPARENT_H
#define GRANDPARENT_H
... contents of grandparent.h
#endif /* !GRANDPARENT_H */

This approach minimally ensures that the contents of the include file are not seen more than once. This is more verbose, requires greater manual intervention, and is prone to programmer error as there are no mechanisms available to the compiler for prevention of accidental use of the same macro name in more than one file, which would result in only one of the files being included. Such errors are unlikely to remain undetected but can complicate the interpretation of a compiler error report. Since the pre-processor itself is responsible for handling #pragma once, the programmer cannot make errors which cause name clashes.

In the absence of #include guards around #include directives, the use of #pragma once will improve compilation speed for some compilers since it is a higher-level mechanism; the compiler itself can compare filenames or inodes without having to invoke the C preprocessor to scan the header for #ifndef and #endif. Yet, since include guards appear very often and the overhead of opening files is significant, it is common for compilers to optimize the handling of include guards, making them as fast as #pragma once.[3][4][5]

Caveats

Identifying the same file on a file system is not a trivial task.[6] Symbolic links and especially hard links may cause the same file to be found under different names in different directories. Compilers may use a heuristic that compares file size, modification time and content.[7] Additionally, #pragma once can do the wrong thing if the same file is intentionally copied into several parts of a project, e.g. when preparing the build. Whereas include guards would still protect from double definitions, #pragma once may or may not treat them as the same file in a compiler-dependent way. These difficulties, together with difficulties related to defining what constitutes the same file in the presence of hard links, networked file systems, etc. has so far prevented the standardization of #pragma once.[citation needed]

The use of #include guard macros allows dependent code to recognize and respond to slight differences in semantics or interfaces of competing alternatives. For example,

#include TLS_API_MACRO /* defined on the command line */

...

#if defined TLS_A_H
... use one known API
#elif defined TLS_B_H
... use another known API
#else
#error "unrecognized TLS API"
#endif

In this case, the direct determination for which API is available would make use of the fact that the include file had advertised itself with its #include guard macro.

The #include directive is defined to represent a programmer's intention to actually include the text of a file at the point of the directive. This may occur several times within a single compilation unit, and is useful for evaluating macro-containing contents multiple times against changing definitions of the macro.

The use of #pragma once, like the use of #include guard macros within an include file places the responsibility upon its authors in order to protect against undesired multiple inclusion. Over-reliance upon either mechanism on the part of programmers by direct, unprotected use of #include directives without their own #include guard will lead to failure when using an include file that has not protected itself with either mechanism.

Portability

Compiler Support
Clang Yes[8]
Comeau C/C++ Yes[9]
Cray C and C++ Yes[10] (since 9.0)
C++Builder Yes[11] (since XE3. classic compiler only.)
Digital Mars C++ Yes[12]
GNU Compiler Collection (GCC) Yes[13] (officially since 3.4[6][14])
HP C/aC++ Yes[15] (since at least A.06.12)
IBM XL C/C++ Yes[16] (since 13.1.1)
Intel C++ Compiler Yes[17]
Microsoft Visual C++ Yes[18][19] (since 4.2)
NVIDIA CUDA Compiler Yes (depending on the underlying host compiler)
Pelles C Yes[20]
ARM DS-5 Yes[21]
IAR C/C++ Yes[22]
Arm Keil Microcontroller Tools: C/C++ compilers Yes[23] (e.g. KEIL ARMCC 5)
OpenWatcom Yes[24]
Oracle Developer Studio C/C++ Yes[25] (since 12.5)
Portland Group C/C++ Yes[26] (since at least 17.4)
TinyCC Yes[27] (since April 2015)
SDCC Yes[28](still Undocumented[29] Oct 2024)
TASKING VX-toolset for TriCore: C Compiler Yes[30] (since v6.2r2)
Texas Instruments Code Generation Tools: C Compiler Yes[31] (e.g. MSP430, ARM, C2000)

References

  1. ^ "once". Microsoft Docs. 3 November 2016. Retrieved 25 July 2019.
  2. ^ "Games from Within: Even More Experiments with Includes". 2005-01-25. Archived from the original on September 30, 2008. Retrieved 2013-08-19.
  3. ^ "The C Preprocessor: 1. The C Preprocessor". Gcc.gnu.org. 1996-02-01. Retrieved 2013-08-19.
  4. ^ ""Clang" CFE Internals Manual — Clang 3.4 documentation". Clang.llvm.org. Retrieved 2013-08-19.
  5. ^ "clang: File manipulation routines". Clang.llvm.org. Retrieved 2013-08-19.
  6. ^ a b "GCC 3.4 Release Series — Changes, New Features, and Fixes". Gcc.gnu.org. Retrieved 2013-08-19.
  7. ^ "should_stack_file() function in GCC source code".
  8. ^ "clang: clang: Pragma.cpp Source File". Clang.llvm.org. Archived from the original on 2014-04-04. Retrieved 2013-08-19.
  9. ^ "Comeau C++ Pre-Release User Documentation: Pragmas". Comeaucomputing.com. Archived from the original on 2013-12-11. Retrieved 2013-08-19.
  10. ^ "CCE 9.0.0 Release Overview Introduction S-5212". Cray Inc. 2019-06-01. Retrieved 2019-09-23.
  11. ^ "#pragma once - RAD Studio XE3". Docwiki.embarcadero.com. 2010-12-02. Retrieved 2013-08-19.
  12. ^ "Pragmas". Digital Mars. Retrieved 2013-08-19.
  13. ^ "Alternatives to Wrapper #ifndef". Gcc.gnu.org. Retrieved 2013-08-20.
  14. ^ "GCC Bug 11569 - there's no substitute for #pragma once". 2003-07-18. Retrieved 2020-10-21.
  15. ^ "HP aC++/HP C A.06.29 Programmer's Guide; March 2016 (AR1603)".
  16. ^ "GCC pragmas". IBM. Retrieved 2015-02-20.
  17. ^ "Diagnostic 1782: #pragma once is obsolete. Use #ifndef guard instead". Intel Developer Zones. Archived from the original on 31 January 2012. Retrieved 4 December 2013. #pragma once should continue to work (Currently NOT deprecated) with the Intel Compiler.
  18. ^ "once (C/C++)". Microsoft Developer Network. Archived from the original on 2016-08-10. Retrieved 2013-08-19.
  19. ^ "once pragma | Microsoft Docs". 3 August 2021.
  20. ^ IDE help/documentation
  21. ^ "ARM Information Center". ARM. Retrieved 2013-12-17.
  22. ^ "IAR C/C++ DevelopmentGuide" (PDF). IAR SYSTEMS. Retrieved 1 March 2023.
  23. ^ "Pragmas recognized by the compiler". Keil.
  24. ^ "#pragma once does not work if files referenced by alternate paths". GitHub. Now it should be fixed in git repository.
  25. ^ "Oracle® Developer Studio 12.5: GCC Compatibility Guide". Oracle. Retrieved 2016-07-26.
  26. ^ "The Portland Group". Retrieved 31 July 2016.
  27. ^ "TinyCC pragma once implementation". Retrieved 19 June 2018.
  28. ^ "Implematation of SDCC pragma parsing, line 122 declaration, line 1393 registration". Retrieved 2024-10-21.
  29. ^ "SDCC Compiler User Guide section 3.16, page 62" (PDF). Retrieved 21 Oct 2024.
  30. ^ "MA160-800 (v6.2r2) March 13, 2018 page 92" (PDF).
  31. ^ "[EXT_EP-8185] Document #pragma once". Embedded Software & Tools. Software Issue Report - Texas Instruments. Archived from the original on Jan 29, 2022.

Read other articles:

Digunakan di:   Franc CFA Afrika Barat (XOF)   Franc CFA Afrika Tengah (XAF) Keduanya franc CFA memiliki nilai tukar tetap ke euro: €1 = F.CFA 655.957. Mata Uang Franc CFA Franc CFA adalah mata uang negara negara di Afrika yang dipakai di negara Guinea-Bissau, Mali, Burkina Faso, Niger, Benin, Togo, Pantai Gading, Republik Afrika Tengah, Kamerun, Guinea Khatulistiwa, Gabon, dan Republik Kongo. Mata uang ini mulai dipakai sejak 1945 menggantikan mata uang Franc CFP. Setiap sat...

 

Mottisfont PrioryLocation within HampshireMonastery informationOrderAugustinianEstablished1201Disestablished22 May 1536Dedicated toThe Priory Church of the Holy Trinity, MottisfontPeopleFounder(s)William BriwereSiteLocationMottisfont, Hampshire, EnglandGrid referenceSU327270Visible remainsparts of church, chapter house and cellarium incorporated into 18th-century mansionPublic accessyesOther informationNational Trust Listed Building – Grade IIOfficial nameMottisfont Abbey HouseDesignated29...

 

العلاقات الكيريباتية المالطية كيريباتي مالطا   كيريباتي   مالطا تعديل مصدري - تعديل   العلاقات الكيريباتية المالطية هي العلاقات الثنائية التي تجمع بين كيريباتي ومالطا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه الم...

Kereta api PapandayanKereta api Papandayan pada hari pertama pengoperasiannya, sedang melaju menuju Stasiun Bekasi TimurInformasi umumJenis layananKereta api antarkotaStatusBeroperasiDaerah operasiDaerah Operasi I JakartaPendahuluPapandayan Ekspres (rute BD-CN via CKP, namun batal beroperasi)Mulai beroperasi24 Januari 2024; 2 bulan lalu (2024-01-24)Operator saat iniKereta Api IndonesiaJumlah penumpang harian520 penumpang per hari[butuh rujukan]Lintas pelayananStasiun awalGambirJu...

 

هذه المقالة تحتاج للمزيد من الوصلات للمقالات الأخرى للمساعدة في ترابط مقالات الموسوعة. فضلًا ساعد في تحسين هذه المقالة بإضافة وصلات إلى المقالات المتعلقة بها الموجودة في النص الحالي. (مارس 2018) باتشو 霸州市  خريطة الموقع تقسيم إداري البلد  الصين[1] التقسيم الأعلى لان...

 

مسجد علي قلي آغا إحداثيات 32°40′04″N 51°40′04″E / 32.667839°N 51.667644°E / 32.667839; 51.667644   معلومات عامة الموقع أصفهان[1]  القرية أو المدينة أصفهان، محافظة أصفهان الدولة  إيران معلومات أخرى تعديل مصدري - تعديل   مسجد علي قلي آغا هو مسجد في أصفهان، إيران، بناه علي قل�...

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Desember 2022. Walking on the Chinese WallLagu oleh Philip Baileydari album Chinese WallSisi-BChildren of the Ghetto (6:49)DirilisUSA: 1985UK: 1985FormatGramophone record 7Direkam1984GenreRock music|RockDurasi5:10LabelColumbia/CBSPenciptaRoxanne Seeman & Billie ...

 

У этого термина существуют и другие значения, см. Агриппа (значения). Агриппа Менений Ланатлат. Agrippa Menenius Lanatus Консул Римской республики 503 до н. э. Рождение VI век до н. э.Древний Рим Смерть 493 до н. э.(-493)неизвестно Род Менении Отец Гай Менений Ланат Мать неизвестно Супруга н...

 

Cet article est une ébauche concernant un chanteur irlandais, un acteur irlandais et un danseur. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Nicky Byrne Nicky Byrne en 2016Informations générales Nom de naissance Nicholas Bernard James Adam Byrne, Jr. Naissance 9 octobre 1978 (45 ans)Dublin, Irlande Activité principale Auteur-compositeur-interprète Activités annexes Présentateur, animateur radio, ...

Berikut ini adalah daftar konser dan acara JKT48: Catatan: Bidang berwarna merah muda ( ) dan bertulisan yang dicoret menandakan bahwa ada jadwal-jadwal penampilan JKT48 yang dibatalkan. Konser atau Acara JKT48 [2014.03.15] JKT48 5th Single Flying Get Launching Concert (Balai Kartini Nusa Indah Theatre) [2014.06.11] JKT48 6th Single Gingham Check Launching Concert (Balai Kartini) [2015.06.13] JKT48 Live in Concert - JKT48 Ada Banyak Rasa, Pilih Suka Rasa Apa? [2016.05.07] The Untold Stor...

 

Nama ini menggunakan cara penamaan Spanyol: nama keluarga pertama atau paternalnya adalah Serra dan nama keluarga kedua atau maternalnya adalah Ferrer. Santo Junípero Serra, O.F.M.Sebuah potret dari Serra pada tahun 1774Rasul CaliforniaLahirMiquel Josep Serra i Ferrer(1713-11-24)24 November 1713Petra, Majorca, SpanyolMeninggal28 Agustus 1784Mission San Carlos Borromeo de Carmelo, Las Californias, Spanyol Baru, Kekaisaran SpanyolBeatifikasi25 September 1988, Lapangan Santo Petrus oleh Pa...

 

此条目序言章节没有充分总结全文内容要点。 (2019年3月21日)请考虑扩充序言,清晰概述条目所有重點。请在条目的讨论页讨论此问题。 哈萨克斯坦總統哈薩克總統旗現任Қасым-Жомарт Кемелұлы Тоқаев卡瑟姆若马尔特·托卡耶夫自2019年3月20日在任任期7年首任努尔苏丹·纳扎尔巴耶夫设立1990年4月24日(哈薩克蘇維埃社會主義共和國總統) 哈萨克斯坦 哈萨克斯坦政府...

Udachny Pembagian administratif Rusiakota Уда́чный (ru) flag of Udachny Tempat Negara berdaulatRusiaRepublik di RusiaSakhaMunicipal districtMirninsky DistrictUrban settlement in RussiaQ23898794 Ibu kota dariQ23898794 NegaraRusia PendudukTotal11.676  (2018 )GeografiLuas wilayah2 km² [convert: unit tak dikenal]Ketinggian380 m SejarahPembuatan1967 Informasi tambahanKode pos678188 Kode telepon41136 OKTMO ID98631109001 OKATO ID98231509000 Lain-lainSitus webLaman resmi Udachny (R...

 

This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. Please help improve this article by introducing more precise citations. (August 2011) (Learn how and when to remove this message) 1983 studio album by CandleMusic Machine II: All About LoveStudio album by CandleReleased1983Recorded1983GenreChildren's music, Christian musicLabelBirdwing recordsCandle chronology Music Machine: The Fruit Of The...

 

Cavalry regiment in the British Army 7th Hussars redirects here. For other uses, see 7th Hussars (disambiguation). 7th Queen's Own HussarsCrest and tie colours of the 7th HussarsActive1689–17141715–1958Country Scotland 1689–1694 England 1694–1697 Scotland 1697–1707  Great Britain (1707–1800) United Kingdom (1801–1958)BranchArmyTypeCavalry of the Line/Royal Armoured CorpsRoleLight CavalrySizeone regimentNickname(s)The Saucy Seventh/The Lilywhite SeventhMotto(s)Honi soit...

Sudafrica ai Giochi della XXV OlimpiadeBarcellona 1992 Codice CIORSA Comitato nazionaleComitato Olimpico e Confederazione Sportiva del Sudafrica Atleti partecipanti93 in 19 discipline Di cui uomini/donne68 - 25 Medagliere Posizione 41ª 0 2 0 2 Cronologia olimpica (sommario)Giochi olimpici estivi 1896 · 1900 · 1904 · 1908 · 1912 · 1920 · 1924 · 1928 · 1932 · 1936 · 1948 · 1952 · 1956 · 1960 · 19...

 

Provincial electoral district in Prince Edward Island, CanadaRustico-Emerald Prince Edward Island electoral districtCoordinates:46°22′44″N 63°20′02″W / 46.379°N 63.334°W / 46.379; -63.334Provincial electoral districtLegislatureLegislative Assembly of Prince Edward IslandMLA    Brad TriversProgressive ConservativeDistrict created1996First contested1996Last contested2023 Rustico-Emerald is a provincial electoral district for the Legislative Ass...

 

1991 IRA attack in Northern Ireland Glenanne barracks bombingPart of the TroublesPart of the UDR barracks after the attackLocationNear Mountnorris, County Armagh, Northern IrelandCoordinates54°14′14.54″N 6°30′17.42″W / 54.2373722°N 6.5048389°W / 54.2373722; -6.5048389Date31 May 1991 23:30 (UTC)Attack typeBombing, gunfireWeaponsTruck bombDeaths3 soldiersInjured10 soldiers4 civiliansPerpetratorProvisional IRA The Glenanne barracks bombing was a large truck bo...

Italian actor and film producer This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Andrea Occhipinti – news · newspapers · books · scholar · JSTOR (June 2023) (Learn how and when to remove this mes...

 

American politician (born 1969) Austin ScottScott in c. 2022Member of the U.S. House of Representativesfrom Georgia's 8th districtIncumbentAssumed office January 3, 2011Preceded byJim MarshallMember of the Georgia House of RepresentativesIn office1996–2011Preceded byHenry BostickSucceeded byTony McBrayerConstituency165th district (1996–2003)138th district (2003–2005)153rd district (2005–2011) Personal detailsBorn (1969-12-10) December 10, 1969 (age 54)August...