开发者

Can you run a function on initialization in c?

开发者 https://www.devze.com 2023-01-03 23:02 出处:网络
Is there an mechanism or trick to run a function when a program loads? What I\'m trying to achieve... void foo(void)

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);

but obviously register_function won't run.

so a trick in C++ is to use initialization to make a function run

something like

int throwaway = register_function(foo);

but that doesn't work in C. So I'm looking for a way around this 开发者_JAVA技巧using standard C (nothing platform / compiler specific )


If you are using GCC, you can do this with a constructor function attribute, eg:

#include <stdio.h>

void foo() __attribute__((constructor));

void foo() {
    printf("Hello, world!\n");
}

int main() { return 0; }

There is no portable way to do this in C, however.

If you don't mind messing with your build system, though, you have more options. For example, you can:

#define CONSTRUCTOR_METHOD(methodname) /* null definition */

CONSTRUCTOR_METHOD(foo)

Now write a build script to search for instances of CONSTRUCTOR_METHOD, and paste a sequence of calls to them into a function in a generated .c file. Invoke the generated function at the start of main().


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.


There is no standard way of doing this although gcc provides a constructor attribute for functions.

The usual way of ensuring some pre-setup has been done (other than a simple variable initialization to a compile time value) is to make sure that all functions requiring that pre-setup. In other words, something like:

static int initialized = 0;
static int x;

int returnX (void) {
    if (!initialized) {
        x = complicatedFunction();
        initialized = 1;
    }
    return x;
}

This is best done in a separate library since it insulates you from the implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消