Question

I see this being done all the time for example in the Linux Kernel. What is the purpose of using the preprocessor commands vs just normal C++ if else block? Is there a speed advantage or something?

Was it helpful?

Solution

A preprocessor changes the C/C++ code before it gets compiled (hence pre processor).

Preprocessor ifs are evaluated at compile-time.

C/C++ ifs are evaluated at run-time.


You can do things that can't be done at run-time.

Adjust code for different platforms or different compilers:

#ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
#include <unistd.h>
#elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems */
#include <windows.h>
#endif

Ensure header file definitions are included only once (equivalent of #pragma once, but more portable):

#ifndef EXAMPLE_H
#define EXAMPLE_H

class Example { ... };

#endif

You can make things faster than at run-time.

void some_debug_function() {
#ifdef DEBUG
    printf("Debug!\n");
#endif
}

Now, when compiling with DEBUG not defined (likely a command line parameter to your compiler), any calls to some_debug_function can be optimized away by the compiler.

OTHER TIPS

Preprocessor is run before the compilation pass, so the compiler won't even see anything that was in the not-taken #if branch.

#if DEBUG
int a;
#else
double b;
#endif

gcc -c -DDEBUG=1 file.c will see "int a"

gcc -c file.c will see "double b"

Preprocessor allows you to actually cut out or paste in to your source file, code to be compiled. If its cut out, its gone, its like a comment, does nothing, is not compiled, produces no code in the binary. Devs will often use this technique to add code only in debug build for debugging purposes or for adding or excluding code for specific operating systems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top