Recently I discovered a nice feature of gcc, the constructor function attribute.

I was writing a C program and I wanted to be able to translate a string that was given as an argument at runtime to the address of a specific function, in order to test different implementations.

The problem with my original approach was that I had to add the functions (the pointer and the name) in an array, which was declared in a different file than the body of the functions. That made difficult for me to keep in sync the functions in the array with the declared functions.

Another approach would be to use the dynamic linking loader and find the address of the function via a call to dlsym (3), but this introduces a lot of unnecessary overhead. I didn't want to dynamically load a library, I just wanted to find a symbol by its name. (Note: There is an interesting paper, about shared libraries written by Ulrich Drepper)

The solution I came up with was to use the constrictor function attribute, which causes the function to be called automatically before execution enters main().

Here is some code:

struct method_s {
        char            *name;
        function_t      *fn;
        struct method_s *next;
};
typedef struct method_s method_t;

#define METHOD_INIT(func) \
void __attribute__((constructor)) func ## _init (void) \
{ \
        method_t *method = method_create( #func, func); \
        method_add(method); \
}

Where, method_create allocates and initializes a method and method_add adds the method to a list, with all the available methods. Now all I had to do in order to put a function in the list, was to add a METHOD_INIT(function).