Friday, July 13, 2018

C #pragma

Description

Pragma directive is a method specified by the C standard for providing additional information to the C compiler.Basically it can be used to turn on or turn off certain features.Pragmas are operating system specific and are different for every compiler.

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:





#pragma token



Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.





#pragma argsused
#pragma exit
#pragma hdrfile
#pragma hdrstop
#pragma inline
#pragma option
#pragma saveregs
#pragma startup
#pragma warn



Let's see a simple example to use #pragma preprocessor directive.





#include<stdio.h>
#include<conio.h>

void func() ;

#pragma startup func
#pragma exit func

void main(){
printf("\nI am in main");
getch();
}

void func(){
printf("\nI am in func");
getch();
}



Output:

I am in func

I am in main

I am in func

By using #pragma startup directive we can call the functions on startup before main function execution





#include<stdio.h>
void print1()
{
printf("Before Main 1\n");
}
void print2()
{
printf("Before Main 2\n");
}
#pragma startup print1 0
#pragma startup print2 1
int main()
{
printf("In Main\n");
return 0;
}



Output

In Main

This will not work when compiled on gcc as it does not recognize this pragma directive.If we want any function to be called before main function by using gcc we have to use __attribute__((constructor (PRIORITY))





#include<stdio.h>
void print1()__attribute__((constructor(100)));
void print2()__attribute__((constructor(101)));
int main()
{
printf("In Main\n");
}
void print1()
{
printf("Before Main 1\n");
}
void print2()
{
printf("Before Main 2\n");
}



Output

Before Main 1

Before main 2

In Main

Examples of #pragma exit function:

Syntax:#pragma exit function_name priority





#include<stdio.h>
void print1()
{
printf("After Main 1\n");
}
void print2()
{
printf("After Main 2\n");
}
#pragma exit print1 0
#pragma exit print2 1
int main()
{
printf("In Main\n");
return 0;
}



OutPut

In Main

For gcc compiler we have to use __attribute__((destructor(priority)))





#include<stdio.h>
void print1()__attribute__((destructor(100)));
void print2()__attribute__((destructor(101)));
int main()
{
printf("In Main\n");
}

void print1()
{
printf("Before Main 1\n");

}

void print2()
{
printf("Before Main 2\n");
}



Output

Before Main 2

Before Main 1




Instagram



No comments:

Post a Comment