I've never understood the need of #pragma once
when #ifndef #define #endif
always works.
I've seen the usage of #pragma comment
to link with other files, but setting up the compiler settings was easier with an IDE.
What are some other usages of #pragma
that is useful, but not widely known?
Edit:
I'm not just after a list of #pragma directives. Perhaps I should rephrase this question a bit more:
What code have you written with #pragma
you found useful?
.
Answers at a glance:
Thanks to all who answered and/or commented. Here's a summary of some inputs I found useful:
- Jason suggested that using
#pragma once
or#ifndef #define #endif
would allow faster compiling on a large-scale system. Steve jumped in and supported this. - 280Z28 stepped ahead and mentioned that
#pragma once
is preferred for MSVC, while GCC compiler is optimised for#ifndef #define #endif
. Therefore one should use either, not both. - Jason also mentioned about
#pragma pack
for binary compatibility, and Clifford is against this, due to possible issues of portability and endianness. Evan provided an example code, and Dennis informed that most compilers will enforce padding for alignment. - sblom suggested using
#pragma warning
to isolate the real problems, and disable the warnings that have already been reviewed. - Evan suggested using
#pragma comment(lib, header)
for easy porting between projects without re-setting up your IDE again. Of course, this is not too portable. - sbi provided a nifty
#pragma message
trick for VC users to output messages with line number information. James took one step further and allowserror
orwarning
to match MSVC's messages, and will show up appropriately such as the Error List. - Chris provided
#pragma region
to be able to collapse code with custom message in MSVC.
Whoa, wait, what if I want to post about not using #pragmas unless necessary?
- Clifford posted from another point of view about not to use
#pragma
. Kudos.
I will add more to this list if the SOers feel the urge to post an answer. Thanks everyone!