Call a function before main [duplicate] Call a function before main [duplicate] c c

Call a function before main [duplicate]


You can have a global variable or a static class member.

1) static class member

//BeforeMain.hclass BeforeMain{    static bool foo;};//BeforeMain.cpp#include "BeforeMain.h"bool BeforeMain::foo = foo();

2) global variable

bool b = foo();int main(){}

Note this link - Mirror of http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14 / proposed alternative - posted by Lundin.


In C++ there is a simple method: use the constructor of a global object.

class StartUp{public:   StartUp()   { foo(); }};StartUp startup; // A global instanceint main(){    ...}

This because the global object is constructed before main() starts. As Lundin pointed out, pay attention to the static initialization order fiasco.


If using gcc and g++ compilers then this can be done by using __attribute__((constructor))

eg::
In gcc (c) ::

#include <stdio.h>void beforeMain (void) __attribute__((constructor));void beforeMain (void){  printf ("\nbefore main\n");}int main (){ printf ("\ninside main \n"); return 0;}

In g++ (c++) ::

#include <iostream>using namespace std;void beforeMain (void) __attribute__((constructor));void beforeMain (void){  cout<<"\nbefore main\n";}int main (){  cout<<"\ninside main \n";  return 0;}