Pages

Monday, December 20, 2010

Macros - #pragma Directive

The pragma Directive allows various instructions to be given to the compiler. Pragmas vary from a compiler to another. If we talk about Turbo C, it has some pragmas that can be used during the program creation.

1. #pragma startup
This directive is used to inform the compiler about the code that we want to run even before "main()".

Example

void welcome()
#pragma startup welcome
#include
void main()
{
    printf("I am the second one to be called");
}

void welcome()
{
    printf("I am running before main()");
}

The above program will print the message inside the welcome() before going to main. Till now we have read and practiced that main() is the first code to run, but as you can see we can write some code that will run before main() also.

2. #pragma exit : Opposite to #pragma startup, #pragma exit will run just before the termination of the program. It can be used to run the code that we want to be the last activity in a program. Let's rewrite the above code to understand its working


void welcome()
void goodbye()
#pragma startup welcome
#pragma exit goodbye
#include
void main()
{
    printf("I am the second one to be called");
}

void welcome()
{
    printf("I am running before main()");
}
void goodbye()
{
    printf("I am the last one");
}

The program will print the messages in the following order
welcome-->main-->goodbye

0 comments:

Post a Comment