Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is formatting buffer for printf?

I working on a constrained embedded system.

Presently we use snprintf to a buffer, then with another statement, print the buffer to the serial port:

  char temp_buffer[256];
  int bytes_written = snprintf(temp_buffer, sizeof(temp_buffer),
                      "Solar system has %d planets\n",
                      10);
  if (bytes_written > 0)
  {
    Serial_Port_Output(temp_buffer, bytes_written);
  }

I want to switch to printf to write directly to the serial port. Per our compiler's documentation, I have intercepted the function call for outputting the data to use the serial port. (The interface uses block writing: an address and the number of characters).

The printf function may use a character buffer for formatting, such as integer or floating point to text.

Questions:

  1. Where is the buffer that printf uses for formatting? (Other inquiring minds want to know, before I make the changes.)
  2. Is this a compiler (platform) dependent issue?

Platform: Arm7tdmi processor, System On a Chip (SOC), IAR EW compiler.

like image 307
Thomas Matthews Avatar asked Dec 09 '22 06:12

Thomas Matthews


2 Answers

This is completely implementation-specific. printf is under no obligation to use any buffer. Of course it has at its disposal the stdio buffer associated with the FILE (stdout in the case of printf) but that may be zero-length if the program turned off buffering with setbuf/setvbuf. It's also possible that printf has an internal buffer; for a proper C implementation this would need to have automatic storage ("on the stack") but a low-quality embedded one without threads might use a static buffer. In any case, printf is specified to work as if by repeated calls to fputc, and it could certainly be implemented this way without any buffer at all.

like image 183
R.. GitHub STOP HELPING ICE Avatar answered Dec 10 '22 18:12

R.. GitHub STOP HELPING ICE


It is library rather than compiler dependent and you should consult the library's documentation and possibly where available the source code. This (perhaps out-of-date) IAR C Library documentation says:

Since a complete formatter demands a lot of space there are several different formatters to choose between. For more information, see the see the IAR C Compiler Reference Guide.

The current IAR compiler reference discusses formatter selection, though in most cases the linker can automatically select the most appropriate formatter. The documentation even discusses further optimisation available if rebuilding the library (for which you presumably need a source license).

Some implementations (not specifically IAR) use significant stack space. If you want full control, you might consider using an open-source implementation such as Tiny printf. It is not a complete ISO implementation, but suitable for many embedded applications.

like image 38
Clifford Avatar answered Dec 10 '22 20:12

Clifford