Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you run a function on initialization in c?

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 using standard C (nothing platform / compiler specific )

like image 845
Keith Nicholas Avatar asked Jun 21 '10 02:06

Keith Nicholas


1 Answers

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

like image 77
bdonlan Avatar answered Oct 08 '22 14:10

bdonlan