0

In file src.cpp

void initz()
{
    // ...
}

I want execute this function when the .exe start,before 'int main()', so i use

void initz()
{
    // ...
}
initz();

but it can't compile success. I know i can use

int initz()
{
    // ...
}
static int a = initz();

but this will create a new variable 'a', although it will not add a new symbol to the linker(can't use outside the .obj file) .but it seems not a good solation.

very important How to avoid create the new variable 'a'? I don't want to use anymore memory space to execute the function. i think it's no necessory.

LiiiiEW
  • 55
  • 6
  • 6
    What's wrong with calling `initz();` as the first line inside the body of `main`? – Nathan Pierson Oct 10 '22 at 14:06
  • I hope this function can called before int main(),just call it in c++ initializer(can't use in c) – LiiiiEW Oct 10 '22 at 14:10
  • If you want a solution that also works in C, edit the question to specify as such. If you want a non-standard way to run code before `main`, with GCC you may use [`__attribute__((constructor))`](https://stackoverflow.com/q/2053029/12122460). – kotatsuyaki Oct 10 '22 at 14:12
  • 4
    Could you clarify why you feel that having an additional static variable is not a good solution? – cigien Oct 10 '22 at 14:12
  • 4
    Why does it have to be executed before `main`? If you can describe that, perhaps there are alternative ways of doing what you need to do. – Ted Lyngmo Oct 10 '22 at 14:15
  • [Call a function before main](https://stackoverflow.com/questions/10897552/call-a-function-before-main). – Jason Oct 10 '22 at 14:16
  • 3
    I think this is an XY-problem. What are you trying to achieve and why? – Thomas Weller Oct 10 '22 at 14:17

0 Answers0