What are some uses of #pragma
in C, with examples?
Putting #pragma once
at the top of your header file will ensure that it is only included once. Note that #pragma once
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
)
what i feel is #pragma
is a directive where if you want the code to be location specific .say a situation where you want the program counter to read from the specific address where the ISR is written then you can specify ISR at that location using #pragma vector=ADC12_VECTOR
and followd by interrupt rotines name and its description
This is a preprocessor directive that can be used to turn on or off certain features.
It is of two types #pragma startup
, #pragma exit
and #pragma warn
.
#pragma startup
allows us to specify functions called upon program startup.
#pragma exit
allows us to specify functions called upon program exit.
#pragma warn
tells the computer to suppress any warning or not.
Many other #pragma
styles can be used to control the compiler.
#pragma startup
is a directive which is used to call a function before the main function and to call another function after the main function, e.g.
#pragma startup func1
#pragma exit func2
Here, func1
runs before main
and func2
runs afterwards.
NOTE: This code works only in Turbo-C compiler. To achieve this functionality in GCC, you can declare func1
and func2
like this:
void __attribute__((constructor)) func1();
void __attribute__((destructor)) func2();
#pragma
is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.
The one I regularly use is #pragma pack(1)
where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.
Pity we don't have a #dogma
yet. That would be fun ;)
To sum it up, #pragma
tells the compiler to do stuff. Here are a couple of ways I use it:
#pragma
can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:
#pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
An older version of libportable does this portably.
#pragma once
, when written at the top of a header file, will cause said header file to be included once. libportable
checks for pragma once support.