Question

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 allows error or warning 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!

Was it helpful?

Solution

Every pragma has its uses, or they wouldn't be there in the first place.

pragma "once" is simply less typing and tidier, if you know you won't be porting the code to a different compiler. It should be more efficient as well, as the compiler will not need to parse the header at all to determine whether or not to include its contents.

edit: To answer the comments: imagine you have a 200kB header file. With "once", the compiler loads this once and then knows that it does not need to include the header at all the next time it sees it referenced. With #if it has to load and parse the entire file every time to determine that all of the code is disabled by the if, because the if must be evaluated each time. On a large codebase this could make a significant difference, although in practical terms (especially with precompiled headers) it may not.

pragma "pack" is invaluable when you need binary compatibility for structs.

Edit: For binary formats, the bytes you supply must exactly match the required format - if your compiler adds some padding, it will screw up the data alignment and corrupt the data. So for serialisation to a binary file format or an in-memory structure that you wish to pass to/from an OS call or a TCP packet, using a struct that maps directly to the binary format is much more efficient than 'memberwise serialisation' (writing the fields one by one) - it uses less code and runs much faster (essential in embedded applications, even today).

pragma "error" and "message" are very handy, especially inside conditional compliation blocks (e.g. "error: The 'Release for ePhone' build is unimplemented", message: "extra debugging and profiling code is enabled in this build")

pragma "warning" (especially with push & pop) is very useful for temporarily disabling annoying warnings, especially when including poorly written third-party headers (that are full of warnings) - especially if you build with warning level 4.

edit: Good practice is to achieve zero warnings in the build so that when a warning occurs you notice it and fix it immediately. You should of course fix all warnings in your own code. However, some warnings simply cannot be fixed, and do not tell you anything important. Additionally, when using third party libraries, where you cannot change their code to fix the warnings, you can remove the 'spam' from your builds by disabling the library's warnings. Using push/pop allows you to selectively disable the warnings only during the library includes, so that your own code is still checked by the compiler.

OTHER TIPS

As you've mentioned I've seen pragmas in visual c++ which tell it to link to a certain library during link time. Handy for a library which needs winsock libs. This way you don't need to modify the project settings to get it linked it. ex: #pragma comment(lib,"wsock32.lib"). I like this because it associates the code that needs the .lib with it, plus once you put that in the file, you can't forget it if you reuse that code in another project.

Also, pragmas for packing of data structures are often useful, pareticually with systems and network programming where the offsets of data members matter. ex:

#pragma pack(push, 1) // packing is now 1
struct T {
char a;
int b;
};
#pragma pack(pop) // packing is back to what it was

// sizeof(T) == sizeof(char) + sizeof(int), normally there would be padding between a and b

You should avoid #pragma wherever possible. #pragma compiler directives are always compiler specific and therefore non-portable. They should be regarded as a last resort.

Moreover, the ISO required behaviour for a compiler that encounters an unrecognised pragma is to simply ignore it. This it may do silently without warning, so if the directive is essential to the correct operation of your code, it may compile but fail to run as expected when compiled with a different compiler. GCC for examples uses very few pragmas, and primarily only for target specific compiler behaviour or compatability with some other compilers. Consequently if you want to ensure portability you end up with constructs like:

#if _MSC_VER
  #pragma PACK(push,1)
#elif   __GNUC__
  // nothing to do here
#else
  #error "Unsupported compiler"
#endif
  struct sPackedExample
  {
      // Packed structure members
#if _MSC_VER
  } ;                              // End of MSVC++ pragma packed structure
  #pragma pack (pop)
#elif   __GNUC__
  }__attribute__((__packed__)) ;   // End of GNU attribute packed structure
#endif

It is a mess, you rapidly cannot see the wood for the trees and the problem becomes worse as you add support for more compilers (which in turn requires knowledge of the pre-defined macros identifying the compiler.

[note:]GCC 4.x does in fact support #pragma pack for MS compatibility, so the above example is somewhat contrived, but this is not true of earlier versions of GCC that may still be in use, or other compilers.

'#pragma once' is particularly problematic, since for a compiler that does not support it, the code will in all but the most trivial cases break when preprocessed. The more verbose but portable solution should be preferred. Visual C++'s application and code generation 'wizards' may use it, but often such code is non-portable in any case. You should be aware when using such code that you are essentially locking your project into Microsoft's tools. This may not be a problem, but I would not recommend using the directive in your own code.

To address your original question: "What code have you written with #pragma you found useful?"; you should rather be considering useful ways of avoiding pragmas perhaps?

It should not perhaps be a question of "usefulness" but rather "necessity". For example a number of embedded systems compilers I have used, use #pragma directives to specify that a function is an interrupt service routine, and therefore has different entry/exit code, and in many cases operates on a different stack. Avoiding such a pragma would require knowledge of the target's assembler language, and would be less efficient when C code is called to handle the interrupt.

This is very similar to sbi's answer but has some additional features.

I've used the following set of macros with #pragma message on Microsoft Visual C++ for some time:

#define EMIT_COMPILER_WARNING_STRINGIFY0(x) #x
#define EMIT_COMPILER_WARNING_STRINGIFY1(x) EMIT_COMPILER_WARNING_STRINGIFY0(x)
#define EMIT_COMPILER_MESSAGE_PREFACE(type) \
    __FILE__ "(" EMIT_COMPILER_WARNING_STRINGIFY1(__LINE__) "): " type ": "

#define EMIT_COMPILER_MESSAGE EMIT_COMPILER_MESSAGE_PREFACE("message")
#define EMIT_COMPILER_WARNING EMIT_COMPILER_MESSAGE_PREFACE("warning")
#define EMIT_COMPILER_ERROR   EMIT_COMPILER_MESSAGE_PREFACE("error")

Used as:

#pragma message(EMIT_COMPILER_WARNING "This code sucks; come back and fix it")

which results in the following text in the build output:

1>z:\sandbox\test.cpp(163): warning : This code sucks; come back and fix it

The output matches the Visual C++ error message format, so errors, warnings, and messages show up in the Error List along with all the other compiler warnings and errors.

The "warning" macro is far more obnoxious than a simple // todo fix this in the code, and helps me to remember to come back and fix something.

The "error" macro is useful because it causes compilation to fail but does not immediately stop the compilation process like the #error directive does.

With VC, I have used this in the past:

#define STRINGIFY( L )       #L
#define MAKESTRING( M, L )   M(L)
#define SHOWORIGIN           __FILE__ "("MAKESTRING( STRINGIFY, __LINE__) "): "

// then, later...

#pragma message( SHOWORIGIN "we need to look at this code" )
// ...
#pragma message( SHOWORIGIN "and at this, too" )

Output:

c:\...\test.cpp(8): we need to look at this code
c:\...\test.cpp(10): and at this, too

You can double-click on it in the output pane and the IDE takes you to the right file and line.

In Visual Studio, C++ preprocessor also supports

#pragma region Some Message Goes Here
...
#pragma endregion

Then you can collapse this region in the code editor so that it only shows the above message. This is analogous to the C# region syntax.

#pragma by definition is for compiler/pre-processor directives that may be platform specific. It looks like you're talking about MSVC++ #pragmas here. You can find their full list, or the full list for gcc.

Other compilers will have completely different lists.

Back on MSVC++, though, one of my favorite pragmas is #pragma warning. I usually build code with "treat warnings as errors" enabled, and then surgically disable certain warnings that I've reviewed to make sure aren't causing problems. This allows the compiler to help me detect more problems during build.

#pragma comment(lib, "WS2_32.lib")

for projects using winsock library

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top