Preprocessor – the #pragma Directive

Behaviour of this preprocessor directive is the same for both C and C++ compilers.
Behaviour of this directive is very likely to vary from one compiler vendor to another.

Purpose

The #pragma directive allows implementation specific control of the compiler.

Format

#pragma command

All preprocessor directives begin with the # symbol. It must be the first character on the line or the first character on the line following optional white space.

Some early compilers flagged an error if # was not the first character on the line.

Spaces or tabs are permitted between the # and pragma, but not escape characters or other symbols or macros. The preprocessor removes white space and concatenates the # and pragma together.

If anything follows the #pragma directive (other than white space) then the program is malformed.

The following are valid uses:

#pragma pack(2)
# pragma once
# /* comments are white space */ pragma long_calls

The following are invalid uses:

// #\ is not a valid preprocessor directive
# \t pragma pack(2)
// #" is not a valid preprocessor directive
# "" pragma once

Use

All #pragma commands are compiler specific, so you need to consult your compiler documentation for details.

If the #pragma command is not recognized, the preprocessor ignores it.

Pragmas are used to pass information to the compiler that cannot be done through the language.

A common use of pragmas is to specify the packing / alignment of data. Normally, a compiler will align data on the processor’s natural boundary (which is usually the same as the processor’s bit size). However, for structures with byte defined data, 8-bit alignment may be required. The following shows byte alignment packing using Microsoft C/C++:

#pragma pack(push) /* save the current packing value */
#pragma pack(1) /* pack on a 1 byte boundary */
struct some_type_with_8_bit_alignment
{
char a;
short b;
long c;
char d;
};
#pragma pack(pop) /* restore the saved packing value */