In C / C ++, what are the build directives for? When should I use them?

4

I came across a C code that used a compilation directive in #ifdef and I do not quite understand what it's for. I found an explanation, but it was not clear. Here's an example policy and the explanation I looked for:

#ifdef <token>
/* code */
#else
/* code to include if the token is not defined */
#endif
  

ifdef checks whether the given token has been #defined earlier in the   file or in an included file. If so, it includes everything between it   and the closing #else or, if no #else is present, the closing #endif.   ifdef can be used with built-in token identifiers set by the compiler to indicate that additional functionality is available.

     

ifdef checks if the token has been previously assigned through   define in the file or even in the same. If yes, include everything in #else or, if #else is not present, #endif.   ifdef can be used with the identifiers of built-in token defined   by the compiler to indicate the availability of functionalities   additional.

Source: link

After all, what are the build directives for? When should I use them? In practice, why are they used?

    
asked by anonymous 04.10.2015 / 01:22

1 answer

5

They are processed before compiling the code itself. In general they instruct the compiler of some actions that should be done with the code.

In this particular example, the conditional compilation directive will check whether a variable exists. Note that this variable was also created by a compilation directive, either in the code or input at the time of the compiler call. The variable is not part of the normal code. It's just like another programming language.

Unlike% code%, if or #ifdef can only check if a specific build variable exists. Just it. The end of it happens with #ifndef .

If the compiler exists, it will consider the code within the directive as apt to be compiled, otherwise it will be discarded and the compiler will not be aware of it. The same goes for #endif .

This is very useful for separating code that should be used when debugging or not, or for choosing specific code for different platforms, or choosing which parts of the code should be included in the final result, placing or removing certain features, helping to optimize, or even handle special situations.

You can also use a #else that allows you to make a more sophisticated condition, or #if or #else , as in the "normal" language.

Another widely-used directive is to include other code files within the main code, especially header files with necessary code declarations. #elif

In addition to #include to define variables and macros and #define to remove the definition, #undef is heavily used to give more compiler-specific instructions, including turning off certain warnings and errors.

There are some less used ones ( #pragma , #line ).

    
04.10.2015 / 01:51