07.04.2013 Views

MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs ... - Microchip

MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs ... - Microchip

MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs ... - Microchip

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Differences Between 16-Bit Device C <strong>and</strong> ANSI C<br />

The weak attribute may be applied to functions as well as variables:<br />

extern int __attribute__((__weak__)) compress_data(void *buf);<br />

int process(void *buf) {<br />

if (compress_data) {<br />

if (compress_data(buf) == -1) /* error */<br />

}<br />

/* process buf */<br />

}<br />

In the above code, the function compress_data will be used only if it is linked in from<br />

some other module. Deciding whether or not to use the feature becomes a link-time<br />

decision, not a compile time decision.<br />

The affect of the weak attribute on a definition is more complicated <strong>and</strong> requires<br />

multiple files to describe:<br />

/* weak1.c */<br />

int __attribute__((__weak__)) i;<br />

void foo() {<br />

i = 1;<br />

}<br />

/* weak2.c */<br />

int i;<br />

extern void foo(void);<br />

void bar() {<br />

i = 2;<br />

}<br />

main() {<br />

foo();<br />

bar();<br />

}<br />

Here the definition in weak2.c of i causes the symbol to become a strong definition.<br />

No link error is emitted <strong>and</strong> both i’s refer to the same storage location. Storage is<br />

allocated <strong>for</strong> weak1.c’s version of i, but this space is not accessible.<br />

There is no check to ensure that both versions of i have the same type; changing i in<br />

weak2.c to be of type float will still allow a link, but the behavior of function foo will<br />

be unexpected. foo will write a value into the least significant portion of our 32-bit float<br />

value. Conversely, changing the type of the weak definition of i in weak1.c to type<br />

float may cause disastrous results. We will be writing a 32-bit floating point value into<br />

a 16-bit integer allocation, overwriting any variable stored immediately after our i.<br />

In the cases where only weak definitions exist, the linker will choose the storage of the<br />

first such definition. The remaining definitions become in-accessible.<br />

The behavior is identical, regardless of the type of the symbol; functions <strong>and</strong> variables<br />

behave in the same manner.<br />

© 2008 <strong>Microchip</strong> Technology Inc. DS51284H-page 19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!