Can you run a function on initialization in c?

前端 未结 3 664
情深已故
情深已故 2020-12-19 07:27

Is there an mechanism or trick to run a function when a program loads?

What I\'m trying to achieve...

void foo(void)
{
}

register_function(foo);
<         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 07:58

    Standard C does not support such an operation. If you don't wish to use compiler specific features to do this, then your next best bet might be to create a global static flag that is initialized to false. Then whenever someone invokes one of your operations that require the function pointer to be registered, you check that flag. If it is false you register the function then set the flag to true. Subsequent calls then won't have to perform the registration. This is similar to the lazy instantiation used in the OO Singleton design pattern.

提交回复
热议问题