Back to Blog

C in 100 Seconds: Preprocessor Directives

Daryl WongDaryl Wong

Video: C in 100 Seconds: Preprocessor Directives — define, ifdef, ifndef | Episode 40 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Preprocessor Directives

The C preprocessor runs before the compiler. It handles lines starting with # — replacing text, including files, and choosing which code to compile.

#define — Constants and Macros

#define PI 3.14159
#define MAX_SIZE 100
#define SQUARE(x) ((x) * (x))

Every occurrence of PI gets replaced with 3.14159 before compilation. SQUARE(5) becomes ((5) * (5)) — a macro with a parameter.

#ifdef — Conditional Compilation

#ifdef DEBUG
  printf("Debug mode is ON
");
#else
  printf("Debug mode is OFF
");
#endif

Only one branch makes it into the final program. If DEBUG is defined, you get the ON message. If not, the OFF message. The other branch is completely removed.

#ifndef — If NOT Defined

#ifndef VERSION
  #define VERSION "1.0.0"
#endif

This defines VERSION only if it does not already exist. This is the pattern used for include guards in header files.

Defining from the Command Line

gcc preproc.c -o preproc          // DEBUG not defined
gcc -DDEBUG preproc.c -o preproc  // DEBUG defined

The -D flag defines a symbol from the command line — no code change needed. Same source, different behavior.

Student Code

Try it yourself: episode40/preproc.c