Can you run a function on initialization in c?

前端 未结 3 663
情深已故
情深已故 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: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.

提交回复
热议问题