Home Conditional Compilation in C++(English)
Post
Cancel

Conditional Compilation in C++(English)

Conditional Compilation in C++

When you’re looking at C++ code, especially in large projects, you’ll often see #ifdef or #ifndef…etc. Many such code snippets display normally in the IDE, while others appear grayed out. What’s going on here? And is it important?

It’s extremely important!!! If you overlook it, the code you’ve painstakingly modified might actually remain unchanged in an incorrect configuration, resulting in bugs that persist, leading to customer complaints and QA tears.

Purpose of Conditional Compilation in C++

Conditional compilation in C++ is a technique to selectively include or exclude sections of code during the compilation process based on conditions. This technique allows programmers to compile different code blocks based on different conditions, thereby achieving functionalities like cross-platform compatibility, debugging modes, etc.

Conditional compilation is typically implemented using preprocessor directives, which start with #, such as #ifdef, #ifndef, #if, etc. Here are some common conditional compilation directives and their meanings:

#ifdef: Compiles the following code block if the specified macro is defined. #ifndef: Compiles the following code block if the specified macro is not defined. #if: Compiles the following code block if the condition expression is true. #else: Compiles the following code block if the previous condition is not met. #elif: Compiles the following code block if the previous condition is not met and the current condition is true. #endif: Ends the code block for conditional compilation.

Once you understand these, reading code becomes a breeze! Haha!

Demonstration

The following demonstrates how to add your own directives in the preprocessor and how it looks in the IDE, along with the final execution result.

First, in the project property page, Configuration Debug: C/C++ -> Preprocessor -> Preprocessor Definitions, add:

TEST_DEBUG

Desktop View

Next, in the project property page, Configuration Release: C/C++ -> Preprocessor -> Preprocessor Definitions, add:

TEST_RELEASE

Desktop View

Switch to Debug configuration

Desktop View

Execution result: Only calls the code snippet in TEST_DEBUG

Desktop View

Switch to Release configuration

Desktop View

Execution result: Only calls the code snippet in TEST_RELEASE

Desktop View

Complete code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

#ifdef TEST_DEBUG
const char* getMode()
{
    return "I am in Debug configuration";
}
#endif


#ifdef TEST_RELEASE
const char* getMode()
{
    return "I am in Release configuration";
}
#endif


int main()
{
    std::cout << "Hello World!\n\n";

    std::cout << getMode() << std::endl;
}

That’s it! It should be clear now! You can continue happy coding!㋡

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍