Can you run a function on initialization in c?

前端 未结 3 652
情深已故
情深已故 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条回答
  • 2020-12-19 07:41

    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().

    0 讨论(0)
  • 2020-12-19 07:46

    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 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题