Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 135 ยท Preprocessor

Conditional Compilation

Learn C conditional compilation: #if, #ifdef and #elif, debug builds, include guards, #pragma once, __STDC_VERSION__, __has_include and #embed.

The same C source file often has to build in different ways: with or without debug output, on Windows and on Linux, with a new C23 compiler and an old one, with an optional library or without it. Conditional compilation lets the preprocessor keep or drop whole blocks of code before the compiler sees them. Code that's dropped isn't compiled at all, so it can even contain calls to functions that don't exist on the current platform.

This lesson covers the conditional directives (#if, #ifdef, #ifndef, #elif, #else, #endif and the C23 additions #elifdef and #elifndef), how to write the conditions, include guards and #pragma once, and the feature checks that portable code relies on: __STDC_VERSION__, platform and compiler macros, __has_include, and a look at C23's #embed.

#if, #elif, #else and #endif

#if takes a constant integer expression. If it's nonzero, the lines up to the matching #elif, #else or #endif are kept; otherwise they're removed. #elif ("else if") and #else work like their C counterparts, and every #if needs an #endif:

C Choosing code with #if and #elif

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Change LOG_LEVEL to 3 or 0 and run again. The removed lines don't just "not run": they disappear before compilation, so they add nothing to the program's size or speed.

What you can use in an #if expression:

  • Integer constants, character constants, and macros that expand to them.
  • Arithmetic, comparison, logical and bitwise operators, and ?:.
  • The defined(NAME) operator (or defined NAME), which is 1 if NAME is a macro and 0 otherwise.

What you can't use: variables, sizeof, casts, enumerators and anything else that requires the compiler. The preprocessor runs first and knows only macros. An identifier that isn't a macro counts as 0, silently. That means #if DEBUGG with a typo is simply false. GCC's -Wundef warns about this; it's worth turning on in real projects.

#ifdef and #ifndef

Often you only care whether a macro exists, not what its value is. #ifdef NAME is short for #if defined(NAME), and #ifndef NAME is short for #if !defined(NAME). C23 adds #elifdef and #elifndef to match:

C Debug builds with #ifdef

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With DEBUG defined, every loop step prints a trace to stderr. Delete the #define DEBUG line and DEBUG_PRINT(...) becomes ((void)0), a harmless expression that compiles to nothing, so the calls can stay in the code. (DEBUG_PRINT uses the variadic macros from Macros.)

In real projects you don't edit the file to switch: the build passes -DDEBUG for debug builds, as shown in Build Tools. #ifndef MAX_ITEMS gives a default that a build can override with -DMAX_ITEMS=100. #elifdef needs a C23 compiler (GCC 12+, Clang 13+); with older ones, write #elif defined(DEBUG).

Tip: #if 0 ... #endif is the standard way to switch off a block of code temporarily. Unlike /* ... */, it works even when the block contains comments, because comments don't nest but #if blocks do. Remove such blocks before committing, or explain why they're there.

Include guards

#include pastes a file's text, so if two headers both include point.h, its contents end up in your file twice. Declarations can usually be repeated, but definitions such as struct point { ... }; can't, and the compiler reports a redefinition error. The classic fix is an include guard: wrap the whole header in #ifndef / #define / #endif.

C
/* point.h */
#ifndef POINT_H
#define POINT_H

struct point {
    double x;
    double y;
};

double point_distance(struct point a, struct point b);

#endif /* POINT_H */

The first time point.h is included, POINT_H isn't defined, so the content is kept and POINT_H gets defined. Every later inclusion finds POINT_H already defined and skips everything up to #endif. Our editor has only one file, but you can watch the mechanism by pasting the "header" twice:

C An include guard at work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Remove the two #ifndef POINT_H lines and their #endifs, and GCC reports error: redefinition of 'struct point'. The guard name must be unique across the project, so use the file name in upper case, possibly with a project prefix (MYLIB_POINT_H). Don't start it with an underscore and a capital letter (_POINT_H): such names are reserved for the implementation, as Keywords and Identifiers explains.

#pragma once

Almost every compiler (GCC, Clang, MSVC, ICC) also supports a one-line alternative:

C
/* point.h */
#pragma once

struct point {
    double x;
    double y;
};

#pragma once tells the compiler to include this file at most once. It's shorter and can't suffer from two headers accidentally choosing the same guard name. It's not part of the C standard, though, and it can be confused by the same file reachable through two different paths (symbolic links, network drives). Many projects use #pragma once; others stick with guards for strict portability. Both are fine; be consistent within a project. Splitting programs into headers is covered in Multi-File Programs.

Checking the C standard version

The macro __STDC_VERSION__ tells you which standard the compiler is using, as a long constant of the form year and month:

Standard __STDC_VERSION__
C99 199901L
C11 201112L
C17 201710L
C23 202311L

(C89/C90 don't define it, except for the 1995 amendment, which uses 199409L.) Code can then use a modern feature when it's available and fall back otherwise:

C Feature checks by standard version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Our editor compiles with -std=c23, so you'll see 202311L. The same file still compiles as C11 with an older compiler, just without the [[nodiscard]] attribute. Indenting directives after the # or before it is allowed and makes nested conditions easier to read. Modern C lists what each standard added.

Platform and compiler checks

Compilers predefine macros that describe the target system and themselves. None of these come from the C standard, but they're stable and widely used:

Macro Defined when
_WIN32 Compiling for Windows (32- and 64-bit)
_WIN64 64-bit Windows
__linux__ Linux
__APPLE__ macOS and iOS
__unix__ Most Unix-like systems (not macOS by default)
__x86_64__, __aarch64__ x86-64 or 64-bit ARM processors (GCC/Clang)
__GNUC__ GCC, and also Clang and others that imitate it
__clang__ Clang
_MSC_VER Microsoft Visual C++
C Detecting platform and compiler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check __clang__ before __GNUC__, because Clang defines __GNUC__ too, for compatibility. Keep platform-specific code in a few small places (a platform.c file or a wrapper function) instead of scattering #ifdef _WIN32 all over a program; the more conditions code has, the more combinations you'd need to test.

__has_include and attribute checks

Some features don't depend on the standard version as much as on what's installed. C23 standardized __has_include, which GCC and Clang have supported for years. It's 1 if a header can be found:

C Optional headers with __has_include

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On our server, <threads.h> exists but <stdbit.h> doesn't (that C23 header needs a newer C library than the one installed), and there's no my_settings.h, so the program uses its defaults. This is how portable code picks up optional features without failing on systems that lack them.

C23 also adds __has_c_attribute(name) to check whether an attribute like [[nodiscard]] or [[fallthrough]] is supported, and GCC and Clang provide __has_builtin for compiler built-ins. On very old compilers these checks may not exist at all, so portable headers first test #if defined(__has_include) before using it.

#embed: including binary data (C23)

C23 adds #embed, which turns the bytes of a file into a comma-separated list of integers at compile time. It replaces the old trick of converting images or fonts into giant C arrays with an external tool:

C
static const unsigned char logo_png[] = {
#embed "logo.png"
};

static const char license_text[] = {
#embed "LICENSE.txt" if_empty(0)
    , 0                         /* add a terminating null character */
};

GCC 15 and Clang 19 support #embed. Our editor compiles a single file, so there's nothing to embed here; the example is read-only. Parameters like limit(n) (embed at most n bytes) and if_empty(...) are part of the standard, and __has_embed("file") checks whether a file can be embedded.

#pragma

#pragma passes implementation-specific instructions to the compiler. Unknown pragmas are ignored (GCC warns about them with -Wall), so they're safe to leave for other compilers. A few common ones:

C
#pragma once                                /* include this header once */

#pragma GCC diagnostic push                 /* silence one warning locally */
#pragma GCC diagnostic ignored "-Wunused-parameter"
void callback(int unused) { }
#pragma GCC diagnostic pop

#pragma pack(push, 1)                       /* MSVC-style packing, also in GCC */
struct wire_header { unsigned char type; unsigned length; };
#pragma pack(pop)

There's also the _Pragma("...") operator (C99), which does the same thing but can appear inside a macro. Packing and its dangers are covered in Padding and Alignment.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. VERBOSE is not defined anywhere. What happens with #if VERBOSE ... #endif?

    In #if expressions, identifiers that aren't macros are replaced by 0. That makes typos silent; -Wundef warns about them.
  2. 2. Which of these can NOT be used in an #if condition?

    The preprocessor runs before the compiler and doesn't know types, so sizeof, casts and variables aren't available. Use static_assert for type checks.
  3. 3. What problem do include guards solve?

    When a header is included twice, its definitions appear twice and cause redefinition errors. The #ifndef/#define/#endif guard skips the content after the first time.
  4. 4. Why should you test __clang__ before __GNUC__?

    For compatibility, Clang defines __GNUC__ (and __GNUC_MINOR__). Test the more specific macro first.
  5. 5. With -std=c23, what is the value of __STDC_VERSION__?

    Each standard has a year-and-month value; C23's is 202311L, C17's is 201710L and C11's is 201112L.

Summary

  • #if, #elif, #else and #endif keep or remove code using constant integer expressions; undefined identifiers count as 0.
  • #ifdef X and #ifndef X test whether a macro exists; C23 adds #elifdef and #elifndef.
  • #if 0 ... #endif disables code safely, even code with comments.
  • Include guards (#ifndef FILE_H / #define FILE_H / #endif) or #pragma once stop a header from being pasted twice.
  • __STDC_VERSION__ (202311L for C23), platform macros (_WIN32, __linux__) and compiler macros (__clang__, __GNUC__, _MSC_VER) let one source file adapt.
  • __has_include (C23, long supported by GCC/Clang) detects optional headers; #embed (C23) includes a file's bytes.
  • #pragma gives compiler-specific instructions; unknown pragmas are ignored.

Next: Predefined Macros and assert