views:

800

answers:

8

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!

+3  A: 

#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.

sblom
+1. Thanks for sharing `#pragma warning.` along with a use case.
Xavier Ho
+9  A: 

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
Evan Teran
+1. The pragma lib is very *very* useful.
paercebal
@Evan, do most compilers add padding by default when we have different sizes of types in a struct like `char` and `int`?
Xavier Ho
@Xavier: Yes. All types have alignment requirements that the compiler enforces, and padding in structs is necessary for that.
Dennis Zickefoose
@Dennis: Thanks a bunch. I was able to confirm it here (http://stackoverflow.com/questions/364483/determining-the-alignment-of-c-c-structures-in-relation-to-its-members). +1 for you.
Xavier Ho
+1 #Pragma Comment I use often
Elemental
-1 This hides linker settings away in source files where it's hard to find. It's pretty easy to waste a lot of time trying to find out why 3rd party code is trying to link against a library only to find one of these gems buried somewhere in the code.
Eric
+9  A: 

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.

Jason Williams
+1. Nicely explained. Can you elaborate about "binary compatibility" briefly?
Xavier Ho
I cannot see how #program once will be any more efficient. The difference, if any would be insignificant (and unmeasurable), and may go either way. Structure packing is useful for a quick-and-dirty fix, but does not address issues of portability and endianness. Data serialisation/de-serialisation is a more robust technique for binary compatability (though more code and lower performance) Better to fix your code than to hide a warning.
Clifford
@Xavier: Lets say you write a structure to a file, and that structure is padded to eight bytes. A different program goes to read that file, but it is expecting a structure with no padding, so it only reads 5 bytes.
Dennis Zickefoose
@Clifford: Thanks for the insight from another point of view. I'll have to read up more on this.
Xavier Ho
@Dennis: How would that matter if the useful information is only contained in those 5 bytes? Please clarify.
Xavier Ho
@Xavier: The useful information *isn't* stored in those five bytes. The program that wrote the data used eight bytes, so whatever information was in the last three got lost.
Dennis Zickefoose
@Dennis: Hmm. I need time on this. Thanks.
Xavier Ho
@Xavier, @Clifford, please see my edits for more explanation.
Jason Williams
@Jason: Haha, I saw it before I saw your comment. Thank you for elaborating your answers!
Xavier Ho
@Xavier: no problem. It's hard to know sometimes how much to explain and how much to leave to the imagination :-)
Jason Williams
"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". That's not true. GCC has an optimisation to spot header include guards and treat them roughly the same as if the guard were external. There is no requirement in the C++ standard that the preprocessor actually go through the motions of reading the file, just that the compilation as a whole produces a correct program. Of course on compilers which lack this optimisation but have #pragma once, the pragma provides the same benefit.
Steve Jessop
@Clifford: For GCC, you are correct. For large projects compiled with Visual C++, you are absolutely incorrect, and the difference can quite noticeable. As such, headers intended for cross-platform compilation should include the guard I added to the following answer: http://stackoverflow.com/questions/2233401/are-redundant-include-guards-necessary/2233408#2233408
280Z28
Very interesting. Thanks Steve.
Xavier Ho
@280Z28, @Jason Williams: Ah, I see your point now. However long compilations are necessary in order to force a coffee break! ;-)
Clifford
Aaaaand.. topic re-edited to reflect 280Z28's comments.
Xavier Ho
Last I checked, Visual C++ also performed the same optimization on #ifndef's. It is a bit picky though, and requires the include guard to enclose *everything* else in the file, as I recall. I'm not sure if it is thrown off by comments outside the include guard, but #includes and other preprocessor stuff outside the guard will definitely ruin the optimization.
jalf
@jalf: Maybe when I get to the point where my program takes over 1 minute to compile, I'll give it a test.
Xavier Ho
+6  A: 

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.

Clifford
+1. Thanks for your effort to put this together! I would have accepted this answer if my topic was about avoiding #pragmas. Another day!
Xavier Ho
@Xavier Ho: I will always tell you what you need to know rather than what you may have asked! ;-)
Clifford
@Clifford: I was considering asking you to post an answer before you posted, but I was hesitant because it's really not answering the topic, but rather the contrary. Still, you read my mind!
Xavier Ho
+1  A: 

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.

sbi
Nice trick! Is this VC-specific?
Xavier Ho
@Xavier: Well, `#pragma` is compiler-specific by its very definition, although some compilers implement similar ones. But `#pragma message` is, TTBOMK, VC-specific (and so is the output format for the VS output pane). ISTR that Borland's compiler implemented it, too, though. There's was a bit different in syntax, but had a VC compatibility mode.
sbi
Gotcha. Thanks for getting back to me.
Xavier Ho
@sbi: I have some macros similar to this (http://stackoverflow.com/questions/2703528/what-code-have-you-written-with-pragma-you-found-useful/2706693#2706693) that have the added feature of adding messages to the Error List; you might be interested in them, just thought I'd give you a heads-up.
James McNellis
@James: I do like the error macro. +1
sbi
A: 
#pragma comment(lib, "WS2_32.lib")

for projects using winsock library

chester89
`using #pragma`? That's new to me. Is this C++?
Xavier Ho
@Xavier Ho, no-no, of course I mean #pragma. sorry, updated the answer
chester89
Thanks for the correction.
Xavier Ho
+1  A: 

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.

Chris O
Huh. Interesting. Are these `#pragma region` code simply ignored at compile time? (The inside will still compile, of course.)
Xavier Ho
Yes of course, the compiler doesn't do anything with the #pragmas, just the code between them, only the preprocessor uses them.
Chris O
The preprocessor and the compiler both ignore `#pragma region`. On the other hand, `#pragma pack` is used exclusively by the compiler - the preprocessor doesn't do struct layouts.
MSalters
@MSalters, right you are, thanks for the correction, #pragma pack is very important.
Chris O
+4  A: 

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.

James McNellis
Ah, one extra layer to separate the errors and warnings. Good trick.
Xavier Ho