C Programming - Beginner to Brilliance / Preprocessors and Macros

Predefined Macros

C provides a set of built-in (predefined) macros that are automatically available in your program. These are mostly used for debugging, logging, or version control, and can help you know more about the code's environment at compile time.

These macros are defined by the compiler and cannot be changed or undefined.


📋 What are Predefined Macros?

These are special macros that provide useful information such as:

Macro

Description

__DATE__

Current date of compilation (e.g. "Jul 02 2025")

__TIME__

Current time of compilation (e.g. "16:32:07")

__FILE__

Name of the current source file

__LINE__

Current line number in the source file

__STDC__

Defined as 1 when the compiler complies with the ANSI C standard


🔍 List of All Predefined Macros

Macro

Example Output

Purpose

__DATE__

"Jul 02 2025"

Date when file was compiled

__TIME__

"16:30:55"

Time of compilation

__FILE__

"main.c"

Name of the current file being compiled

__LINE__

27

Line number in current file

__STDC__

1

Indicates compiler follows ANSI C standard

__STDC_VERSION__

199901L, 201112L, etc.

Shows the C version (if defined)

__STDC_HOSTED__

1 or 0

Indicates whether the implementation is hosted or freestanding (usually 1)


🧪 Practical Example Using Predefined Macros

🔎 LINE will print the actual line number in the source file where it is used. If you move the statement, the number will change accordingly.


🧠 Why and Where to Use Predefined Macros?

Use Case

Description

✅ Debugging

Show which file and line caused an issue

🧪 Logging

Print compilation time to confirm code freshness

🚧 Error Handling

Combine with #error to alert developers

📂 File tracking

Automatically know the current source file

📐 Version Control

Detect compiler version and behavior


📌 Using __LINE__ & __FILE__ for Custom Error Messages

#define error(msg) printf("Error: %s in %s at line %d\\n", msg, __FILE__, __LINE__)

int main() {
    error("Something went wrong!");
    return 0;
}
Error: Something went wrong! in main.c at line 6

🧰 This is a manual version of assert(), great for early-stage debugging without using libraries.