What are some uses of #pragma
in C, with examples?
I would generally try to avoid the use of #pragmas if possible, since they're extremely compiler-dependent and non-portable. If you want to use them in a portable fashion, you'll have to surround every pragma with a #if
/#endif
pair. GCC discourages the use of pragmas, and really only supports some of them for compatibility with other compilers; GCC has other ways of doing the same things that other compilers use pragmas for.
For example, here's how you'd ensure that a structure is packed tightly (i.e. no padding between members) in MSVC:
#pragma pack(push, 1)
struct PackedStructure
{
char a;
int b;
short c;
};
#pragma pack(pop)
// sizeof(PackedStructure) == 7
Here's how you'd do the same thing in GCC:
struct PackedStructure __attribute__((__packed__))
{
char a;
int b;
short c;
};
// sizeof(PackedStructure == 7)
The GCC code is more portable, because if you want to compile that with a non-GCC compiler, all you have to do is
#define __attribute__(x)
Whereas if you want to port the MSVC code, you have to surround each pragma with a #if
/#endif
pair. Not pretty.
#pragma
is for compiler directives that are machine-specific or operating-system-specific, i.e. it tells the compiler to do something, set some option, take some action, override some default, etc. that may or may not apply to all machines and operating systems.
See msdn for more info.
My best advice is to look at your compiler's documentation, because pragmas are by definition implementation-specific. For instance, in embedded projects I've used them to locate code and data in different sections, or declare interrupt handlers. i.e.:
#pragma code BANK1
#pragma data BANK2
#pragma INT3 TimerHandler
All answers above make nice explanations for #pragma
but I wanted to a add small example
I just want to explain a simple OpenMP example
that demonstrate some uses of #pragma
to doing its work
OpenMp
briefly
is an implementation for multi-platform shared-memory parallel programming (then we can say it'smachine-specific
oroperating-system-specific
)
let's go to the example
#include <stdio.h>
#include <omp.h>// compile with: /openmp
int main() {
#pragma omp parallel num_threads(4)
{
int i = omp_get_thread_num();
printf_s("Hello from thread %d\n", i);
}
}
the output is
Hello from thread 0
Hello from thread 1
Hello from thread 2
Hello from thread 3
Note that the order of output can vary on different machines.
now let me tell you what #pragma
did...
it tells the OS to run the some block of code on 4 threads
this is just one of many many applications
you can do with the little #pragma
sorry for the outside sample OpenMP