"Static variable bug in Zephyr RTOS driver sync logic"

View profile for Chethan Singh

LGSoft India || Capgemini Engineering || Embedded Firmware developer || RTOS || Linux

The Day a static Variable Broke My Driver Sync Logic I recently spent hours debugging a strange bug while building a multi-instance hardware driver on Zephyr RTOS. I had two different drivers that needed to synchronize their initialization using a shared flag. One driver would signal when reset was done, and the other would wait for it. Seemed simple… until it wasn’t 😅 ⚡ The Bug I wrote a helper like this inside a header file: // sync_helper.h static inline void wait_for_ready(void) { static bool ready = false; if (!ready) { printf("Waiting...\n"); while (!ready) { /* wait */ } } } Then I included it in two .c files: // master.c #include "sync_helper.h" void master_start(void) { // do reset... ready = true; // supposed to wake up others } // slave.c #include "sync_helper.h" void slave_start(void) { wait_for_ready(); // waits forever... } 🔴 Result: The slave got stuck forever. Even though the master set ready = true, the slave never saw it. Why? Because static inside a header creates a separate copy for each .c file. So master.c and slave.c each had their own private ready flag in different memory locations. It wasn’t a race condition — it was symbol scope. 😅 🛠 The Fix I changed it to a proper global: // sync_helper.h #pragma once extern bool ready; static inline void wait_for_ready(void) { while (!ready) { /* wait */ } } // sync_helper.c #include "sync_helper.h" bool ready = false; Now all .c files see the same ready variable, and the synchronization works perfectly. 💡 Lessons Learned static inside a header = one copy per .c file (not shared) extern in header + one definition in .c = single shared global This kind of bug looks like a race condition but is really a linkage issue ⚙️ Embedded Takeaway In embedded development, how your code links is just as important as how it runs. A few misplaced static keywords can silently break cross-driver logic and cost you hours of head-scratching. 💬 Have you ever fought an “invisible global” like this? Drop your war stories below Let’s save each other some debugging pain! #EmbeddedSystems #ZephyrRTOS #CProgramming #Firmware #Debugging #RealTime #RTOS #Linker #StaticVsExtern

  • diagram
Eric Poulsen

Embedded HW & SW developer

1d

1) This (compilation units, and how "include" works) is basic C 2) Your first example code won't compile 3) Using variables in this way to synchronize is the wrong way to do this for multi-threaded environments.

Like
Reply

Please consider "volatile" prefix, when defining variable (ready) , apart from removing static

See more comments

To view or add a comment, sign in

Explore content categories