问题描述
是否可以在编译时或运行时以某种方式检查该变量是否具有 static
存储类说明符?
Is it possible somehow to check at compile time or at run time that variable has static
storage-class specifier?
示例:
static int v1;
int v2;
bool r1 = is_static(v1); /* true */
bool r2 = is_static(v2); /* false */
推荐答案
好吧,原来我之前的回答对静态全局变量不起作用,所以我设计了这个程序,可以检查全局变量是否被声明为静态.它的工作方式是 dysym() 在符号表中找不到静态全局变量,所以我只检查它的输出.它还使用布尔值引用变量,以确保它确实存在.
Ok, turns out that my previous answer didn't work for static global variables, so I have devised this program that can check whether a global variable is declared static. The way it works is that dysym() can't find static globals in the symbol table, so I just check it's output. It also references the variable with a boolean and, to ensure it actually exists.
#include <stdio.h>
#include <dlfcn.h>
char* a = "hello, world";
static char* b = "hello, world";
#define is_static(name) \
(is_sym_static(#name) && &name)
_Bool is_sym_static(const char* const name)
{
void* hdl = dlopen(NULL, 0); // TODO: optimise by only calling this once.
return dlsym(hdl, name) == NULL;
}
int main(int argc, char** argv)
{
printf("%i\n", is_static(a)); // prints 0
printf("%i\n", is_static(b)); // prints 1
}
这必须用-ldl -Wl,--export-dynamic
编译,以确保所有变量都在符号表中结束.这不适用于局部变量,但我们可以将它与我之前的答案结合起来......
This must be compiled with -ldl -Wl,--export-dynamic
, to ensure that all variables end up in the symbol table. This doesn't work for local variables, but we can combine it with my previous answer and...
#include <stdio.h>
#include <dlfcn.h>
#include <sys/resource.h>
static char* stack_start;
#define is_static(name) \
(is_addr_static(&name) && is_sym_static(#name) && &name)
_Bool is_sym_static(const char* const name)
{
void* hdl = dlopen(NULL, 0); // TODO: optimise by only calling this once.
return dlsym(hdl, name) == NULL;
}
_Bool is_addr_static(void* var)
{
struct rlimit stack;
getrlimit(RLIMIT_STACK, &stack); // TODO: optimise by only calling this once.
char* stack_end = stack_start - stack.rlim_cur;
return !((char*)var < stack_start && (char*)var > stack_end);
}
char* a = "hello, world";
static char* b = "hello, world";
int main(int argc, char** argv)
{
char _;
stack_start = &_;
char* c = "hello, world";
static char* d = "hello, world";
printf("%i\n", is_static(a)); // prints 0
printf("%i\n", is_static(b)); // prints 1
printf("%i\n", is_static(c)); // prints 0
printf("%i\n", is_static(d)); // prints 1
}
现在检测全局和局部静态变量.然而,我认为没有必要这样做,因为局部静态和全局静态是根本不同的东西.
This now detects both global and local static variables. I see no reason to need this however, since local static and global static are fundamentally different things.
这篇关于C:在编译时或运行时检查该变量是否具有静态存储类说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!