我有一个只适用于静态局部变量的宏(因为它使用内联汇编符号来提取有关变量的数据)。我需要一种方法来强制宏的输入确实是一个静态局部变量:
正确:
func f()
{
static int x;
my_macro(x);
}
不正确:
func f()
{
int x;
my_macro(x);
}
我使用 GCC for C(没有 C++)。
最佳答案
您可以使用以下技巧:
#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 为非静态变量发出错误“initializer element is not constant”。
关于c - 如何添加静态断言来检查变量是否是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5645695/