Course contentsShow
← C
Lesson 784 of 1,21911. The Preprocessor and BuildFree lesson

Using `#error` to stop compilation

Using #error to stop compilation

What you'll learn: How to use the #error directive to intentionally crash the build process when specific safety conditions aren't met.

The "Emergency Brake" of C

Imagine you are building a piece of furniture that must be painted blue. If the factory runs out of blue paint, you don’t want them to just shrug and send you a red chair; you want the entire assembly line to stop immediately so the mistake can be fixed.

In C programming, the #error directive is your emergency brake. It tells the preprocessor: "If you reach this line, stop everything, display a specific message, and fail the build." Unlike a standard printf which happens while your program is running, #error happens while your program is being created.

Why use it?

We usually combine #error with conditional compilation (like #if or #ifndef). It acts as a safety guard for your code’s requirements. For example, if your program only works on 64-bit systems, you don't want someone to successfully compile it for a 32-bit system only for it to crash later. You want the compiler to refuse to build it in the first place.

How it looks in code

The directive is followed by whatever text message you want the programmer to see in their terminal or IDE.

#include <stdio.h>

// Imagine our program requires a specific version 
// of a library to be safe.
#define SETTINGS_VERSION 1

#if SETTINGS_VERSION < 2
    #error "Settings version is too old! Please update to Version 2 or higher."
#endif

int main() {
    printf("This will never print because the build will fail above.");
    return 0;
}

When you try to compile the code above, the compiler won't produce an executable file. Instead, it will stop and output: fatal error: #error "Settings version is too old! Please update to Version 2 or higher."

When to pull the brake

You’ll typically see #error used for:

  1. Platform checks: Ensuring the code is being compiled for the right Operating System.
  2. Configuration guards: Making sure the user hasn't forgotten to define a critical setting.
  3. Safety limits: Preventing the code from being built if a constant value (like a buffer size) is set dangerously low.

By using #error, you ensure that a broken configuration never makes it to the user.

Key takeaway

The #error directive forces the compiler to stop and display a custom message, preventing the creation of a program that doesn't meet your requirements.