🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Newlib, Syscalls & printf on Bare-Metal ARM
Understand how Newlib and Newlib-nano bring the C standard library to embedded systems, and learn to implement low-level syscalls to enable printf over UART or SWO.
1. What is Newlib?
Newlib is an implementation of the C standard library specifically designed for embedded systems. It provides the familiar C functions — printf, malloc, memcpy, strlen, string formatting, and more — in a form that can run on bare-metal systems with no OS.
Newlib ships with the ARM GCC cross-toolchain as the default C standard library. When you compile with arm-none-eabi-gcc, Newlib is available.
Newlib vs glibc vs uClibc
| Library | Interfaces | Target | Size |
|---|---|---|---|
| GNU libc (glibc) | ISO C, POSIX, System V, XPG | Desktop Linux | Very large |
| uClibc | ISO C, POSIX, System V | Embedded Linux | Medium |
| Newlib | ISO C only | Bare metal ARM | Small-medium |
| Newlib-nano | ISO C (minimal subset) | Bare metal MCU | Very small |
Key fact: Newlib is available under a permissive license (MIT/BSD-like) and is the default in the ARM GCC embedded toolchain. It can run with no OS at all — perfect for bare-metal STM32 development.
2. Newlib-nano: Minimized for MCUs
The full Newlib library is comprehensive but too large for MCUs with limited flash (64–512 KB). Newlib-nano is a stripped-down version introduced by ARM that provides the same API but with much smaller code and data footprint.
Key Differences
- Simplified printf/scanf (no float support by default — add with
-u _printf_float) - Smaller malloc implementation
- Reduced feature set but same function signatures
- Enabled with
--specs=nano.specs
Shell — Enable Newlib-nano
# Link with newlib-nano (smaller C library)
arm-none-eabi-gcc \
-mcpu=cortex-m4 -mthumb \
--specs=nano.specs \ # use newlib-nano
--specs=nosys.specs \ # stub syscalls (or provide your own syscalls.c)
-T stm32f407.ld \
-Wl,--gc-sections \
-o firmware.elf \
main.o startup.o syscalls.o
# If you need printf with float support:
arm-none-eabi-gcc ... -u _printf_float ...
nosys.specs vs Your Own Syscalls
--specs=nosys.specs— provides stub syscalls that do nothing (no UART output, malloc may not work). Useful to get a quick build without errors.- Your own syscalls.c — implement
_write,_read,_sbrk, etc. targeting your specific hardware. This is the correct approach for real projects.
3. Why Syscalls Are Needed
Newlib’s philosophy: implement all hardware-independent C library functionality, and rely on a small set of low-level “system calls” that you implement for your specific hardware.
printf(“Hello!”); malloc(100);
C standard library: printf formats string → calls _write()
_write() → send to UART or ITM
_sbrk() → manage heap memory
_read() → receive from UART
USART2 registers / ITM register / memory
Newlib handles all the complex formatting (converting integers to strings, handling %d, %f, %s, etc.) and calls your simple _write() function with a ready-formatted byte buffer. Your job is just to send those bytes to the right place.
4. Key Syscalls to Implement
You must implement these functions in syscalls.c. Newlib will call them when needed:
| Syscall | Called by | Purpose |
|---|---|---|
_write(fd, buf, count) | printf, puts, fwrite | Write bytes to a file descriptor (fd=1 for stdout) |
_read(fd, buf, count) | scanf, getchar, fread | Read bytes from a file descriptor (fd=0 for stdin) |
_sbrk(increment) | malloc, calloc, realloc | Extend the heap — return next available memory address |
_close(fd) | fclose | Close a file descriptor |
_lseek(fd, offset, whence) | fseek | Seek within a file |
_fstat(fd, st) | fstat | Get file status |
_isatty(fd) | isatty | Check if fd is a terminal |
_exit(status) | exit() | Terminate program |
5. Implementing _write over UART
The most common implementation redirects stdout to USART2 on the STM32F4 (PA2=TX, PA3=RX).
C — syscalls.c (_write via USART2)
#include <stdint.h>
#include <errno.h>
#include <sys/stat.h>
/* USART2 register base */
#define USART2_BASE 0x40004400UL
#define USART2_SR (*((volatile uint32_t*)(USART2_BASE + 0x00)))
#define USART2_DR (*((volatile uint32_t*)(USART2_BASE + 0x04)))
#define USART_SR_TXE (1U << 7U) /* TX data register empty */
/* _write is called by Newlib's printf when it has formatted bytes to output */
int _write(int fd, char *buf, int count)
{
(void) fd; /* ignore file descriptor — always send to USART2 */
for (int i = 0; i < count; i++) {
/* Wait until TX data register is empty */
while (!(USART2_SR & USART_SR_TXE));
/* Write byte to data register */
USART2_DR = (uint32_t) buf[i];
}
return count; /* return number of bytes written */
}
/* Stub for read — return error if not implementing input */
int _read(int fd, char *buf, int count)
{
(void) fd; (void) buf; (void) count;
errno = ENOSYS;
return -1;
}
/* Stubs required by Newlib but not needed in simple projects */
int _close(int fd) { (void)fd; return -1; }
int _lseek(int fd, int offset, int whence) { (void)fd;(void)offset;(void)whence; return -1; }
int _fstat(int fd, struct stat *st) { (void)fd; st->st_mode = S_IFCHR; return 0; }
int _isatty(int fd) { (void)fd; return 1; }
void _exit(int status) { (void)status; while(1); }
USART2 must be initialized first! The _write function assumes USART2 is already configured (baud rate, GPIO pins). Call your USART2 init function from main() or from Reset_Handler before any printf calls.
6. Implementing _write over ITM/SWO
If you are debugging with SWD and have access to the SWO pin, you can redirect printf to the ITM trace port. This appears in the IDE’s SWV console with no extra hardware.
C — _write via ITM (SWO trace)
#define ITM_PORT0_U8 (*((volatile uint8_t*)0xE0000000UL))
#define ITM_TER (*((volatile uint32_t*)0xE0000E00UL)) /* Trace Enable Register */
#define ITM_TCR (*((volatile uint32_t*)0xE0000E80UL)) /* Trace Control Register */
int _write(int fd, char *buf, int count)
{
(void) fd;
for (int i = 0; i < count; i++) {
/* Check if ITM is enabled and stimulus port 0 is enabled */
if ((ITM_TCR & 1U) && (ITM_TER & 1U)) {
/* Wait until port is ready */
while (ITM_PORT0_U8 == 0);
ITM_PORT0_U8 = (uint8_t) buf[i];
}
}
return count;
}
7. Implementing _sbrk for malloc
_sbrk(increment) is called by malloc() to grow the heap. It must return the next available SRAM address and advance an internal pointer. The heap grows upward from the end of .bss.
C — _sbrk implementation
#include <errno.h>
/* Linker defines the end of .bss — heap starts here */
extern uint32_t _ebss;
extern uint32_t _estack; /* top of SRAM = bottom of stack */
#define HEAP_MIN_HEADROOM 256U /* keep 256 bytes gap between heap and stack */
void *_sbrk(int increment)
{
static uint8_t *heap_ptr = NULL;
if (heap_ptr == NULL) {
heap_ptr = (uint8_t *) &_ebss; /* first call: start at end of .bss */
}
uint8_t *new_ptr = heap_ptr + increment;
/* Check that heap does not collide with stack */
if ((uint32_t) new_ptr + HEAP_MIN_HEADROOM > (uint32_t) &_estack) {
errno = ENOMEM;
return (void *) -1; /* out of memory */
}
void *old_ptr = heap_ptr;
heap_ptr = new_ptr;
return old_ptr;
}
Safety tip: Always include the heap/stack collision check in _sbrk. Without it, a large malloc could silently overwrite the stack, causing unpredictable crashes much later in execution.
8. Linking with Newlib-nano
Updated Makefile
CC = arm-none-eabi-gcc
OBJCOPY = arm-none-eabi-objcopy
CPU = -mcpu=cortex-m4 -mthumb
CFLAGS = $(CPU) -O2 -g3 -Wall -Wextra -ffunction-sections -fdata-sections
LDFLAGS = $(CPU) \
-T stm32f407.ld \
--specs=nano.specs \ # use newlib-nano
-Wl,--gc-sections \
-Wl,-Map=firmware.map
TARGET = firmware
SRCS = main.o startup.o syscalls.o
all: $(TARGET).elf $(TARGET).bin
$(TARGET).elf: $(SRCS)
$(CC) $(LDFLAGS) -o $@ $^
$(TARGET).bin: $(TARGET).elf
$(OBJCOPY) -O binary $< $@
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
C — main.c using printf
#include <stdio.h>
#include <stdint.h>
extern void usart2_init(uint32_t baud);
int main(void)
{
usart2_init(115200);
uint32_t count = 0;
while (1) {
printf("Hello from ARM Cortex-M4! count=%lu\r\n", count++);
/* simple delay */
for (volatile uint32_t i = 0; i < 800000; i++);
}
}
9. Programming Exercises
Exercise 1 — Printf Over UART
Implement the full syscalls.c with _write, _sbrk, and stubs. Initialize USART2 at 115200 baud and print a counter value every 500 ms. Use a serial terminal (PuTTY, minicom) to verify output.
C — USART2 init skeleton
void usart2_init(uint32_t baud)
{
/* Enable GPIOA and USART2 clocks */
RCC_AHB1ENR |= (1U << 0U); /* GPIOA */
RCC_APB1ENR |= (1U << 17U); /* USART2 */
/* Configure PA2 as AF7 (USART2_TX) */
GPIOA_MODER |= (2U << (2U * 2U)); /* alternate function mode */
GPIOA_AFRL |= (7U << (4U * 2U)); /* AF7 = USART2 */
/* Set baud rate: BRR = fclk / baud (at 16 MHz, 115200 baud → 138.9) */
USART2_BRR = (uint32_t)(16000000.0f / baud + 0.5f);
/* Enable USART and TX */
USART2_CR1 |= (1U << 13U) | (1U << 3U); /* UE | TE */
}
Exercise 2 — malloc on Bare Metal
After implementing _sbrk, test dynamic memory allocation:
C — malloc test
#include <stdlib.h>
#include <stdio.h>
void test_malloc(void)
{
char *buf = (char *) malloc(64);
if (buf == NULL) {
printf("malloc failed!\r\n");
return;
}
snprintf(buf, 64, "heap at %p\r\n", (void*)buf);
printf("%s", buf);
free(buf);
}
10. FAQ
Why does my printf not output anything even after implementing _write?
Common reasons: (1) USART2 not initialized before the first printf call. (2) The USART clock is not enabled (RCC_APB1ENR). (3) GPIO pins not configured as alternate function. (4) Baud rate mismatch between MCU and terminal. (5) Newlib’s internal printf buffer isn’t being flushed — add \n to your format string, or call fflush(stdout), or disable buffering with setvbuf(stdout, NULL, _IONBF, 0) in main.
Does –specs=nosys.specs cause any problems?
nosys.specs provides stub implementations of all syscalls that simply return error codes. printf will call _write but nothing will be transmitted. malloc will call _sbrk which returns -1 (failure). It’s only useful for: (1) getting a binary to link without errors for size analysis, or (2) projects that genuinely don’t need I/O or heap. For any real embedded application, always provide your own syscalls.c.
What is the –specs=rdimon.specs option?
rdimon.specs enables semihosting — a mechanism where printf output is redirected through the debugger to the host PC terminal. It works when you are running under a debugger (like GDB + OpenOCD). However, if the board runs without a debugger, each semihosting call (BKPT instruction) will trigger a HardFault. Never ship code compiled with rdimon.specs. It’s only for early debug convenience.
Quick Knowledge Check
1. When Newlib’s printf calls _write(), what does _write() receive in the buf parameter?
- A. The raw format string (e.g., “count=%d”)
- B. The fully formatted output string (e.g., “count=42”)
- C. An integer representing the format specifier
- D. Binary-encoded struct of arguments
Check Answer
2. What does _sbrk() return when the heap has no more memory?
- A. NULL (0)
- B. 0xFFFFFFFF
- C. (void*)-1 and sets errno=ENOMEM
- D. The current heap top without advancing it
Check Answer
3. Which linker flag enables the smaller Newlib-nano library?
- A. –specs=nosys.specs
- B. –specs=rdimon.specs
- C. –specs=nano.specs
- D. -lnano

2 Comments