Call Function Before main Function using C++

Call Function Before main Function using C++

In C++, the main function is always the official entry point of a program. However, sometimes we want to execute certain code before main starts. For example, we may need to set up logging, initialize libraries, or perform some one-time setup before the program runs.

When a C++ program starts, all global and static objects are constructed before main executes. This means if we define a global object whose constructor calls our function, that code will run first.

Here's an example:

#include <iostream>

struct InitializeApp {
    InitializeApp() {
        std::cout << "Initialize function" << std::endl;
    }
} initializeApp;

int main() {
    std::cout << "Main function" << std::endl;

    return 0;
}

Explanation:

  • We define a struct InitializeApp with a constructor that prints specified text.
  • We create a global object initializeApp.
  • When the program starts, before entering main, C++ automatically constructs all global objects.
  • This triggers the constructor of initializeApp, which runs before anything inside main.

If we run the program, we'll see:

Initialize function
Main function

Leave a Comment

Cancel reply

Your email address will not be published.