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

Feature toggles via command line `-D`

Feature toggles via command line -D

What you'll learn: How to turn code features on or off during the build process without changing a single line of your source code.

The "Light Switch" in your code

Imagine you are building a car. Sometimes you want to install a sunroof, and sometimes you don't. Instead of redesigning the whole car every time, you simply leave a space for the sunroof and decide whether to "activate" it when the car is on the assembly line.

In C, we do this using the #ifdef (if defined) preprocessor directive. This acts as a gatekeeper. If a specific "label" exists, the code inside the gate is compiled. If not, the compiler acts like that code doesn't even exist.

Using the -D flag

Normally, you define labels inside your code using #define. However, there is a much more powerful way: defining them at the moment you compile.

Most C compilers (like GCC or Clang) allow you to use the -D flag. This stands for Define. By typing -DDEBUG in your terminal, you are telling the compiler, "For this specific build, act as if #define DEBUG is written at the top of every file."

Seeing it in action

Here is a program that behaves differently depending on whether a PREMIUM flag is set during the build:

#include <stdio.h>

int main() {
    printf("Welcome to the App!\n");

    #ifdef PREMIUM
    printf("Status: Premium Member - All features unlocked.\n");
    #else
    printf("Status: Free Version - Please upgrade for more features.\n");
    #endif

    return 0;
}

If you compile this normally with gcc main.c, you will see the "Free Version" message. But, if you compile with the toggle:

gcc -DPREMIUM main.c -o app

The compiler sees the -DPREMIUM flag, satisfies the #ifdef condition, and includes the premium message in the final executable. The "Free Version" code is completely discarded and won't even be in the final program file.

Why this matters

This is incredibly useful for:

  1. Debugging: Enable extra logging only when you are troubleshooting.
  2. Platforms: Include specific code for Windows and different code for Mac.
  3. Trial Versions: Create "Lite" and "Pro" versions of your software from the exact same source code.

Key takeaway

The -D flag allows you to pass configuration settings from your terminal directly into your code, enabling "feature toggles" at compile time.