Open In App

How to call some function before main() function in C++?

Improve
Improve
Like Article
Like
Save
Share
Report

Since it is known that main() method is the entry point of the program. Hence it is the first method that will get executed by the compiler. But this article explains how to call some function before the main() method gets executed in C++. How to call some function before main() function? To call some function before main() method in C++,

  1. Create a class
  2. Create a function in this class to be called.
  3. Create the constructor of this class and call the above method in this constructor
  4. Now declare an object of this class as a global variable.
  5. Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.

Below is the implementation of the above approach: 

CPP




// C++ program to call some function
// before main() function
 
#include <iostream>
using namespace std;
 
// Class
class GFG {
 
public:
    // Constructor of the class
    GFG()
    {
 
        // Call the other function
        func();
    }
 
    // Function to get executed before main()
    void func()
    {
        cout << "Inside the other function"
             << endl;
    }
};
 
// Global variable to declare
// the object of class GFG
GFG obj;
 
// Driver code
int main()
{
    cout << "Inside main method" << endl;
    return 0;
}


How will this get executed? Now when the program will get executed, the global variable will get created before calling the main() method. 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().

In C++, you can call a function before the main() function using the constructor attribute. This attribute allows you to specify a function that will be automatically called before main().

Here’s an example:

C++




#include <iostream>
 
using namespace std;
 
void my_function() __attribute__ ((constructor));
 
void my_function() {
    cout << "This function is called before main()" << endl;
}
 
int main() {
    cout << "Inside main()" << endl;
    return 0;
}


Output:

This function is called before main()
Inside main()

In this example, we define a function called my_function() and declare it using the constructor attribute. This function will be automatically called before main(). Inside the function, we simply print a message to the console. In main(), we print another message to the console.

Note that the order of execution of constructor functions is not guaranteed, so if you have multiple functions with the constructor attribute, there is no guarantee which one will be executed first.



Last Updated : 11 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads