Tuesday, August 23, 2016

How to call a function before the main function and after 'return 0' line

Some applications needs to call a function before the main function takes the control for loading a specific value form somewhere or after the program dies for saving settings or something like that but, how?

Its very simple.

__attribute__

This peace of code has two options or two parameters to pass.
If constructor is passed, the function will be executed before the main function.
Unlike, if destructor is passed, the function will be executed after int main returns 0

Examples :


1- Executing before main function


#include iostream
using namespace std;

void beforemain(void)__attribute__((constructor));

void beforemain(void)
  {
     cout<<"hi befor main\n";
  }
           
int main()
  {
      cout<<"main\n";
      return 0;
  }


2- Executing after closing the program


#include iostream
using namespace std;

void aftermain(void)__attribute__((destructor));

void aftermain(void)
   {
        cout<<"bye after main\n";
   }
          
int main()
   {
        cout<<"main\n";
        return 0;
    }

Pretty easy and straightforward, right !

No comments:

Post a Comment