0

In GCC, If a variable is declared with weak attribute, and, in (static) linking time, no definition is found, the variable will have address zero, i.e., if a pointer is initialized with the address of the variable, the pointer will be NULL, as the following code snippets illustrate:

foobar.c:

extern int foo __attribute__((weak));
extern int bar;

int *a[] = {&foo, &bar};

main.c:

#include <diag/Trace.h>

//int foo;
int bar;
extern int *a[];

int main(void) {
    trace_printf("%p, %p", a[0], a[1]);
    return 0;
}

The output is: 0, 0x20000120 (I'm using arm-none-eabi-gcc 5.4.1)

The question is: although the behavior is expected, no document mentioned it. Could anyone point me to any material explaining this behavior? Thanks!

dingcurie
  • 121
  • 6

1 Answers1

0

I'm don't think I'd expect that, I'd assume GCC would do the same thing as if the weak attribute wasn't present. The documentation is:

https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

...so this looks like undocumented/undefined behaviour.

James Antill
  • 2,825
  • 18
  • 16
  • But that's the way GCC actually behaves, so it could be said that that's expected by the authors of GCC, too. It's also implemented in IAR, as its manual explicitly says: "The linker will not ..., nor will the lack of a definition for a weak reference result in an error. If no definition is included, the address of the object will be zero." – dingcurie Nov 25 '16 at 00:09
  • No, if that's what they expected it to always do they'd document it as doing that. That's what undocumented/undefined means, it still does _something_ and that thing might be useful to you ... but it might not always do that. – James Antill Dec 18 '16 at 23:30