C Refresher

Compilation (GCC)

Before you flash code to an ESP32, you should understand how C code turns into a program that a computer can run.


Interpreted vs Compiled

Languages like Python are interpreted. A program (the Python interpreter) reads your script line-by-line and executes it instantly.

C is a compiled language. The processor cannot read C code. It only understands pure binary machine code (1s and 0s). We use a Compiler to translate our human-readable C code into machine code.

The Compilation Pipeline

Compiling a C program isn't just one step; it's a 4-step pipeline hidden behind a single command.

  1. Preprocessing: The compiler looks for lines starting with # (like #include <stdio.h>). It literally copy-pastes the contents of stdio.h into your file, and replaces any macros (#define MAX_TEMP 80) with their actual values.
  2. Compilation: Translates the expanded C code into Assembly Language (human-readable instructions tied to the specific CPU architecture, like ARM or x86).
  3. Assembly: Translates the Assembly code into raw binary object files (.o).
  4. Linking: Combines your object files with the standard libraries (like the math library for printf) to create the final, runnable executable (.exe on Windows, or an ELF file on Linux/ESP32).

Compiling Your First Program Locally

Before writing code for microcontrollers, it's highly recommended to write and test simple C logic on your own computer. To do this, you need a C compiler installed on your host machine (usually GCC - GNU Compiler Collection).

1. Write the Code

Create a file named hello.c:

c
1#include <stdio.h>
2
3int main() {
4 printf("Hello from my computer!\n");
5 return 0;
6}

2. Compile It

Open your terminal and run the GCC compiler:

bash
gcc hello.c -o hello
  • gcc is the compiler program.
  • hello.c is your source file.
  • -o hello tells the compiler to name the output executable "hello".

3. Run It

bash
./hello

(You should see "Hello from my computer!" printed to the terminal).


Cross-Compilation

When you use idf.py build for the ESP32, it uses a Cross-Compiler.

A normal compiler creates an executable meant to run on the same type of processor that compiled it (e.g., your Intel/AMD laptop).

A Cross-Compiler runs on your laptop, but generates machine code for a completely different processor architecture (like the Xtensa or RISC-V cores inside an ESP32). This is why embedded toolchains are so large and complex!

Previous
Introduction to C