Oftentimes in classrooms, we are taught that the main function is the ‘main’ function in any program! Is this an undisputed truth? In reality, this is the default behavior of the compilers we use. The compiler has a predefined set of rules according to which:
- The main() function has a default priority of 0, which is the highest.
- Priorities from 0 to 63 are reserved for use by C libraries.
- Priorities from 64 to 99 are kept as a second reserve if the number of library function in a code exceeds 63.
- Any user defined function starts with a priority of 100.
- The maximum explicitly defined priority can be 254.
Thus, it is obvious that the main() works with the highest priority at a program startup.
But the C programming language has a scope for changing the priority such that, main() has a priority shift from startup to exit, i.e. it has a higher priority on exit than on startup. This can be done with the #pragma directive.
The #pragma can help us to set priorities of out user defined functions, at startup as well at exit. In this code I have implemented the #pragma directive to create a function ‘disp_start()’ which has a higher priority of 60 than main(), whose priority has been lowered from 0 to 70.
#include
void disp_start();
void main();
void disp_end();
#pragma startup main 70
#pragma startup disp_start 60
#pragma exit disp_end
static int a=1;
void disp_start()
{
FILE *fp=fopen("nomain.cpp","r");
char c='a';
while(c!=EOF)
{
putch(c=fgetc(fp));
}
fclose(fp);
cout<<"nnStarting first priority functionn";
cout<<"Value of X is initially"<
Howeve, there are some things to keep in mind. The #pragma wont’ always change priorities to anything specified. Most of the time it is on availability.
The highest priorities of 0, 1 and 2 cannot always be assigned to all functions, and are machine dependent. An attempt to assign these priorities may result in a processor fault in some machines on runtime.
Any call to a library function, whose priority runs into the explicitly defined area, will overwrite the explicit priority definition and make space for itself.
Chinmoy Kanjilal is the geek behind Techarraz. This is where he rants about his adventures with technology. Get to know him better, and connect with him on social networks.
the code written over here is giving three errors when i tested it in the bloodshed Dev Cpp that multiple declaration of void main() is it compiler specific one should keep in mind while using #pragma pre processor directive
#pragma is not compiler specific, though this code needs some modification for gcc compatibility. Change return of main and use new style headers with namespaces. Use your brain if you are using another compiler!