Programming‎ > ‎C++‎ > ‎Programming Tips‎ > ‎Misc‎ > ‎

Calling a Function Before Program's Startup

Certain applications need to invoke startup functions that run before the main program starts. For example, polling, billing, and logger functions must be invoked before the actual program begins. The easiest way to achieve this is by calling these functions from a constructor of a global object. Because global objects are conceptually constructed before the program's outset, these functions will run before main() starts. For example:

class Logger
{
public:
  Logger() 
  { 
   activate_log();
  }
};
Logger log; /*global instance*/

int main()
{
  record * prec=read_log();
  //.. application code
}

The global object log is constructed before main() starts. During its construction, log invokes the function activate_log(). Thus, when main() starts, it can read data from the log file.

Comments