6 years, 1 month ago.

How does printf retargeting works?

Hello, I'm writing mbed Notebook about retargeting printf to print on whatever developer wants (LEDs, LCDs, segger RTT...) on Nordic nrf52DK. The process is quite simple, one just needs to write _write_r function and printf will call it (instead of printing on UART which is the default for nrf52 on mbed). My problem is I do not understand what's going on under the hood. Here's my function declaration

extern "C" int _write_r(int file, char *ptr, int len)

and that works great!

The problem is if I define the upper function with "_write" name (as it should be by standard libs since "original" functions are WEAK defined), I got multiple definitions error because of the function

extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsigned int length, int mode)

is defined here: mbed-os/platform/mbed_retarget.cpp

My questions are: why _write_r works, how linker knows when to call _write_r and when to call _write function. Thank you.

Be the first to answer this question.