Possible Duplicate:
Is main() really start of a C++ program?
Is possible to call my function before program's startup? How can i do this work in C++
or C
?
Possible Duplicate:
Is main() really start of a C++ program?
Is possible to call my function before program's startup? How can i do this work in C++
or C
?
You can have a global variable or a static
class member.
1) static
class member
//BeforeMain.h
class 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 instance
int 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;
}
In C++ it is possible, e.g.
static int dummy = (some_function(), 0);
int main() {}
In C this is not allowed because initializers for objects with static storage duration must be constant expressions.
I would suggest you to refer this link..
http://bhushanverma.blogspot.in/2010/09/how-to-call-function-before-main-and.html
For GCC compiler on Linux/Solaris:
#include
void my_ctor (void) __attribute__ ((constructor));
void my_dtor (void) __attribute__ ((destructor));
void
my_ctor (void)
{
printf ("hello before main()\n");
}
void
my_dtor (void)
{
printf ("bye after main()\n");
}
int
main (void)
{
printf ("hello\n");
return 0;
}
$gcc main.c
$./a.out
hello before main()
hello
bye after main()