45

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?

Community
  • 1
  • 1
Nick
  • 10,309
  • 21
  • 97
  • 201
  • 18
    Is there a compelling reason you cannot just make the call immediately after entering main() but before any of your other code executes? Why is pre-main() a requirement? – Omaha Jun 05 '12 at 12:46
  • 3
    why not call this function at main begin? – Alessandro Pezzato Jun 05 '12 at 12:47
  • 3
    What is it that you want to do? If you further explain your actual problem you might get suggestions on the design (rather than the technique). While you can do what you ask for, I would rethink a design that depends on this. – David Rodríguez - dribeas Jun 05 '12 at 12:48
  • 4
    The answers you got will do what you want but be aware that order of evaluation isn't well defined so if you have two of them there is no telling which will run first, so making one of them depend on the results of the other is bad things waiting to happen. This bug is so common it has its own name: the static order initialization fiasco. – stonemetal Jun 05 '12 at 12:52
  • 1
    I was reading about logger and I thought it was usefu know how start a method before the program starts. – Nick Jun 05 '12 at 12:52

5 Answers5

51

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.

noob
  • 8,982
  • 4
  • 37
  • 65
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 5
    Note: the `class` itself is spurious here, just building a global (whatever) is sufficient. – Matthieu M. Jun 05 '12 at 13:15
  • 3
    Just be aware of [this subtle bug](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14). The function called cannot be allowed to depend on any static resources. You should write it as you would write a re-entrant function. – Lundin Jun 05 '12 at 13:44
  • 1
    I believe this to be technically incorrect. AFAIR the function is not required to be called before `main` and can be delayed until `b` is needed. Or maybe it was just the observable state had to be the same. – Pubby Jun 05 '12 at 15:46
  • @Pubby I believe that actually the order is enforced, but granted I'm not going to look for the quote in the standard. :) – Luchian Grigore Jun 05 '12 at 17:29
  • 1
    An additional warning, if that code ever lands in a static linux library (lib*.a): if not told otherwise the linker will ignore any unused variable including initialisation -> foo() will never be called. – josefx Jun 05 '12 at 20:35
  • @Lundin Yes, that is a bug that bit me twice before, and it's really easy to forget not to use any of your `extern`'d globals (they will be 0's, not the initial values you give them in some other .cpp) – bobobobo Nov 03 '13 at 16:11
  • Incorrect: Since `b` is never used, **the compiler is free to never call** `b = foo()`. Only guarantee is that `b = foo()` is called before `b`'s first use, not before `main`. – c z Jul 20 '23 at 14:36
  • @cz including the case where foo() has side-effects? – Luchian Grigore Aug 21 '23 at 11:04
38

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.

VinGarcia
  • 1,015
  • 12
  • 19
gliderkite
  • 8,828
  • 6
  • 44
  • 80
  • Any part of the initialization, really, including arguments passed to a constructor. – Ben Voigt Jun 05 '12 at 12:48
  • 4
    Just be aware of [this subtle bug](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14). The function called cannot be allowed to depend on any static resources. You should write it as you would write a re-entrant function. – Lundin Jun 05 '12 at 13:44
23

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;
}
Eight
  • 4,194
  • 5
  • 30
  • 51
  • 7
    Except this isn't C nor C++, it is GCC non-standard extensions. – Lundin Jun 05 '12 at 13:40
  • I had a need to call a `void function` before main recently, and tried adapting this answer, but it crashed. I tested at cpp.sh as well as code chef: same result both cases. If I use printf instead of cout, there is no crash. Any idea why? – StoneThrow Mar 31 '17 at 22:23
  • 1
    @StoneThrow I suspect your function was called before `cout` was constructed. – Tomeamis Jan 28 '19 at 12:29
21

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.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
2

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()
kapilddit
  • 1,729
  • 4
  • 26
  • 51