I have code
#include <stdlib.h>
void *gg = malloc(55);
int main(int argc, char **argv)
{
return 0;
}
gcc fail to compile but g++ works.
So, I just want to make sure that the malloc calling happens before main is exectued.
Simple answer: you cannot.
The main function always acts as a driver function and calls other functions. We can also write function call as a parameter to function.
The function which is declared outside the main( ), which is a global declaration, can be accessed by any function outside and inside the main() function.
In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. The C programming language supports recursion, i.e., a function to call itself.
What you do is allowed in C++. The C++ standard has a whole section on "Dynamic initialization of non-local variables".
Looking at the assembly generated by GCC for your code is instructive:
Here the initializers are called through two generated functions, _GLOBAL__sub_I_gg
(which is called before main
) which in turn calls __static_initialization_and_destruction_0
.
It is within the body of the latter function you will find the call to malloc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With