Mplab X Compiler 95%
Pro tip: Enable the . It outputs a .map file that reads like a confessional—showing exactly where every variable sinned (i.e., consumed a cycle). 2. Optimization Levels: The "Surgeon" vs. The "Wrecking Ball" The default optimization ( -O1 ) is safe. But -O3 (for XC32) or -Os (for XC8) is where things get interesting.
You write a delay function:
But what if I told you that the MPLAB X compiler suite (XC8, XC16, XC32) is not just a translator? It is a co-pilot . When wielded correctly, it can predict hardware race conditions, eliminate entire functions at compile time, and even write assembly better than you can. mplab x compiler
Also, enable . The compiler will tell you exactly which function blows your stack budget. This is not debugging; this is prophecy. 5. Literally Writing Assembly Inside C (Without the Headache) When you must bit-bang a WS2812 LED or toggle a pin in 50 ns, inline assembly is your friend. But the XC compilers have a trick: Extended Asm .
__asm__ volatile ("bsf %0, %1" : "=r"(PORT) : "r"(0)); The compiler will allocate the register for you. It won't clobber the WREG. It's civilised. Pro tip: Enable the
void delay_ms(int ms) { for(int i=0; i<ms*1000; i++); } At -O0 , it works. At -O3 , the compiler notices the loop has no side effects. It doesn't just optimize the loop—it deletes the entire function . Your LED now toggles at 100 MHz. Poof.
Never assume the compiler is stupid. Use volatile strategically, not habitually. The XC32 compiler’s -fno-delete-null-pointer-checks is a lifesaver, but its -faggressive-loop-optimizations is a trap for the unwary. 3. The Mystical __attribute__ Directives This is where the compiler stops being a tool and starts being a wizard. XC compilers support GCC-style attributes plus Microchip-specific ones. __attribute__((persistent)) Place a variable in .persistent memory. It survives a device reset without re-initialization. Perfect for "why did I reboot?" state machines. __attribute__((interrupt(automatic_priority))) XC32 automatically handles the shadow register set and prologue/epilogue. Did you know that writing void __ISR(_TIMER_1_VECTOR, ipl2) my_handler(void) tells the compiler exactly which priority level to use, saving 7 cycles of software context saving? __attribute__((space(prog))) On XC16 (dsPIC), this forces a constant into program memory (flash) instead of RAM. Your 4KB lookup table now costs zero RAM. The compiler generates PSV windows for you automatically. 4. The "Free" Static Analysis You Are Ignoring Open your project properties. Go to MPLAB XCxx Compiler > Diagnostics . Turn on -Wconversion and -Wshadow . Optimization Levels: The "Surgeon" vs
And that while(1); ? The compiler leaves it alone. Some things are sacred. Author’s note: This article was compiled with XC8 v2.36, XC16 v2.10, and a healthy respect for the -fno-builtin flag.