Can you run the function on initialization in c?

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

What I'm trying to achieve ...

void foo(void)
{
}

register_function(foo);

but obviously register_function will not work.

so the trick in C ++ is to use initialization to run the function

sort of

int throwaway = register_function(foo);

but this does not work in C. Therefore, I am looking for a way around this using standard C (it has no specifics for the platform / compiler)

+5
source share
3 answers

If you use GCC, you can do this with a function attribute constructor, for example:

#include <stdio.h>

void foo() __attribute__((constructor));

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

int main() { return 0; }

However, in C there is no portable way to do this.

, . , :

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

CONSTRUCTOR_METHOD(foo)

build script CONSTRUCTOR_METHOD .c. main().

+14

C ​​. , , false. , - , , . , , true. . , OO Singleton.

+3

, gcc constructor .

The usual way to provide some presetting (other than simply initializing the variable for the compilation time value) is to make sure that all functions that require presetting. 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, as it isolates you from the implementation.

0
source

All Articles