j0lama
j0lama

Reputation: 77

Assign an address to a function pointer in a define in C

I want to assign an address to a function pointer in a define, is it possible? I want to do this in a define:

void (* uart_puts)(char *) = (void(*)(char * )) 0x0000000000008248;
char (* msg) = (char *) 0x7fb8;

Thanks!

Update:

Im compiling this function and I want to get both variables in a .h to simplify my .c file. I dont know if it's possible but ideally get these definitions in two define statements.

void function()
{
    void (* uart_puts)(char *) = (void(*)(char * )) 0x0000000000008248;
    char (* msg) = (char *) 0x7fb8;
    while (1)
    {
        uart_puts(msg);
    }
}

Upvotes: 1

Views: 157

Answers (1)

KamilCuk
KamilCuk

Reputation: 141623

You can do:

#define uart_puts ((void(*)(char*))0x000000008248)

Then use it:

void f() { 
    uart_puts("a"); 
}

The text "uart_puts" will be exapnded by the preprocessor. Remember, that this means, that all symbols/texts "uart_puts" after the macro definition will be substituted.

But it would be better to store the information, that it's a function macro:

#define uart_puts(str)  ((void(*)(char*))0x000000008248)(str)

That way you can call uart_puts(smth), but it's not possible to get the function pointer.

Also you can declare a static variable in your header file, usually with const:

static void (* const uart_puts)(char *) = (void (*)(char*)) 0x0000000ffda;

This is another way of declaring constants in header files in C, usually using compilers that the programmer knows, will optimize the static const variable and remove it, if it is unused.

Upvotes: 1

Related Questions