Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function before main [duplicate]

Tags:

c++

c

main

startup

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?

like image 331
Nick Avatar asked Jun 05 '12 12:06

Nick


People also ask

Can we call function before Main?

Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method. Hence we can easily call the function before the main().

Does function order matter in C?

The order of functions inside a file is arbitrary. It does not matter if you put function one at the top of the file and function two at the bottom, or vice versa. Caveat: In order for one function to "see" (use) another function, the "prototype" of the function must be seen in the file before the usage.

How to use void function C?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.


2 Answers

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.

like image 150
Luchian Grigore Avatar answered Sep 22 '22 13:09

Luchian Grigore


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.

like image 24
gliderkite Avatar answered Sep 25 '22 13:09

gliderkite