GCC weak attribute on variable declaration
Asked Answered
U

1

-1

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!

Unpretentious answered 23/11, 2016 at 4:54 Comment(0)
C
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.

Chaunceychaunt answered 23/11, 2016 at 5:32 Comment(2)
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."Unpretentious
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.Chaunceychaunt

© 2022 - 2024 — McMap. All rights reserved.