Search code examples
c++clinkerweak-references

How to define an object whose address is null?


I am wondering how I can define an object in C whose reference will be null?

// definition of foo 
...
void * bar = &foo; // bar must be null

There is some ways I could find to do it, but none fit my needs.

__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

Actually, I would prefer a standard compliant solution (c99), but anything working will be ok.


Edited: The reason to do this is that bar will not always be null. Here is a more relevant example:

// 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);
}

Of course this is still not very relevant, because I can use #if in my condition. The project involves in fact big structures, a lot of files, a few compilers, some cpu targets, and many programmers who generate bugs with a probability exponential to the complexity of the syntax they use. It is why I would like a simple macro to declare my foo object.


Solution

  • You are trying to create a symbol with an address of zero. Your last example is probably the only way of doing this within the C compiler / language.

    The approach that is most likely to solve your problem is to look at the input file to the linker program. Most linkers allow you to define the label foo as zero.

    In a unix ld script this is just: foo = 0 ;