What is pragma in C? Or how will you execute functions before and after main function in C program?

Short Answer
Views 612

Answer:

In C, #pragma is a preprocessor directive that provides additional information to the compiler. It is a way to give special instructions to the compiler about how to process the code. The #pragma directive is followed by an identifier that indicates the specific action to be taken.

Regarding executing functions before and after the main function in a C program, you can use the #pragma startup and #pragma exit directives.

  1. Before main Function:

  2. 
    #include <stdio.h>
    
    void startup_function(void) {
        printf("Function executed before main\n");
    }
    
    #pragma startup startup_function
    
    int main() {
        printf("Inside main function\n");
        return 0;
    }
    
    

 

  1. The #pragma startup directive is used to specify a function (startup_function in this case) that will be executed before the main function.

  2. After main Function:

  3. 
    #include <stdio.h>
    
    void exit_function(void) {
        printf("Function executed after main\n");
    }
    
    #pragma exit exit_function
    
    int main() {
        printf("Inside main function\n");
        return 0;
    }
    
    
  1. The #pragma exit directive is used to specify a function (exit_function in this case) that will be executed after the main function.

It's important to note that the usage of #pragma directives is compiler-specific, and not all compilers support these directives. The examples provided here are based on compilers that support these specific directives, like Turbo C or certain versions of GCC. Always check the documentation of your compiler for the supported directives and their behavior.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of C Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.