cal*_*doa -1 c c++ linker weak-references
我想知道如何在C中定义一个对象,其引用将为null?
// definition of foo
...
void * bar = &foo; // bar must be null
Run Code Online (Sandbox Code Playgroud)
有一些方法我可以找到它,但没有一个符合我的需要.
__attribute__((weak)) extern int foo; //not working with cygwin/gcc 3.4
__attribute__((at(0))) int foo; //only with rvds
#define foo (*(int*) 0) //cannot be embedded in a macro
Run Code Online (Sandbox Code Playgroud)
实际上,我更喜欢符合标准的解决方案(c99),但任何正常工作都可以.
编辑:这样做的原因是bar不会总是为空.这是一个更相关的例子:
// macro that will define foo to a real object or to *null
DECL(foo);
int * bar = &foo;
if(bar) {
// we can call func
func(bar);
} else {
// bar undefined
exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
当然这仍然不是很相关,因为我可以在我的条件下使用#if.该项目实际上涉及大型结构,大量文件,一些编译器,一些cpu目标,以及许多程序员,他们生成的错误概率指数与他们使用的语法的复杂性呈指数关系.这就是为什么我想要一个简单的宏来声明我的foo对象.