Tuesday, 3 November 2015

How to use #pragma directive

#pragma directive is used to set priority of function so that they can be called before or after main.

startup pragma : It allows the program to specify function that will be called before main.

#pragma startup <function name> [priority]


exit pragma : It allows the program to specify function that will be called after main.

#pragma exit <function name> [priority]


Here,
<function name>
Must be declared or defined before the pragma line is reached and it must not take any arguments and must return void.
eg: void function(void);

[priority]
0 = Highest priority
0-63 = Used by C libraries
64 = First available user priority
100 = Default priority 
255 = Lowest priority

Note: 
1. Do not use priorities from 0 - 63 because these are used by C libraries.
2. Function with higher priorities are called first at startup and last at exit.
3. Lesser number - higher priority (Sometimes this might be confusing).


Example Code:


#include<stdio.h>
void first();
void second();

#pragma startup first 105
#pragma startup second 
#pragma exit first 105
#pragma exit second

void main(){
printf("I am in main.\n");

}

void first(){

printf("I am in first. \n");

}

void second(){

printf("I am in second\n");

}


Output:
I am in second.
I am in first.
I am in main.
I am in first.
I am in second.

No comments:

Post a Comment