Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a static assert to check if a variable is static?

I have a macro which works well only on static local variables (since it uses inline assembly notation to extract data about the variable). I need a way to enforce that the input to the macro is indeed a static local variable:

correct:

func f()
{
    static int x;
    my_macro(x);
}

not correct:

func f()
{
    int x;
    my_macro(x);
}

I work with GCC for C (no C++).

like image 320
Ofir Hermesh Avatar asked Oct 17 '25 07:10

Ofir Hermesh


1 Answers

You can use following trick:

#define ASSERT_LOCAL_STATIC(v) static void *p_ ## v = &v

void fn()
{
    int nonstatic_var = 0;
    static int static_var = 0;

    ASSERT_LOCAL_STATIC(static_var);
    ASSERT_LOCAL_STATIC(nonstatic_var);
}

GCC issues an error "initializer element is not constant" for non-static variables.

like image 197
Sergej Zagursky Avatar answered Oct 19 '25 21:10

Sergej Zagursky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!