Pragmas in C language



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.

Examples of some of the pragmas  are #pragma startup,#pragma exit


Example of #pragma startup:

Syntax:  #pragma startup <function name> [priority]

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;

}


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");

}


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;

}


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");

}


Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto