11. Preprocessor & ToolingIntermediate9 min read
C Preprocessor Directives, Macros & Header Guards
Harness the C preprocessor: #define constants and function-like macros, conditional compilation (#ifdef, #ifndef), header guards, and predefined macros.
Key Takeaways & Core Concepts
- The preprocessor runs before the compiler, performing text substitutions and conditional pruning.
- Header guards (
#ifndef HEADER_H,#define HEADER_H,#endif) prevent double inclusion errors. - Function-like macros (
#define SQUARE(x) ((x)*(x))) execute inline with zero function call overhead. - Conditional compilation (
#ifdef DEBUG) allows compiling debug code or OS-specific implementations.
Header Guards & Function-Like Macros
When projects scale across multiple .h headers, circular dependencies cause redefinition errors. Header guards prevent this:
C Code Example
1#ifndef CODEZOV_MATH_H
2#define CODEZOV_MATH_H
3
4// Declarations here...
5
6#endif // CODEZOV_MATH_H
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
6 lines
Preprocessor Macros & Predefined Constants
1#include <stdio.h>
2
3#define PI 3.14159265359
4#define MAX(a, b) ((a) > (b) ? (a) : (b))
5
6#define DEBUG_LOG(msg) \
7 printf("[DEBUG] %s:%d in %s(): %s\n", __FILE__, __LINE__, __func__, msg)
8
9int main(void) {
10 int num1 = 45, num2 = 80;
11
12 DEBUG_LOG("Calculating maximum value...");
13 printf("MAX(%d, %d) = %d\n", num1, num2, MAX(num1, num2));
14 printf("Compiled on: %s at %s\n", __DATE__, __TIME__);
15
16 return 0;
17}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
17 lines
Note: __FILE__, __LINE__, __func__, __DATE__, and __TIME__ are standard predefined macros supported by all ANSI/ISO C compilers.
Practice & AssessmentC Programming Complete Course
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 1 correct(0 attempted)
1
Why should macro arguments be enclosed in parentheses in function-like macros (e.g. #define SQUARE(x) ((x)*(x)))?
Intermediate