Include header files
-
instruction:
#include
- use: Insert the specified header file content into the current source file, so that the current source file can use the functions, variables, type definitions, etc. declared in the header file. This helps to modularize and reuse the code and improves development efficiency.
- Give an example:
#include <> // Includes standard input and output header files to use printf, scanf and other functions#include "" // Contains custom header files
Defining a macro
-
instruction:
#define
- use: Can define constants, functional macros, etc. When defining constants, it can improve the readability and maintainability of the code; defining functional macros can improve the execution efficiency of the program to a certain extent, but pay attention to its side effects.
- Give an example:
#define PI 3.1415926 // Define constant PI#define MAX(a, b) ((a) > (b)? (a) : (b)) // Define macro functions,Find the maximum value of two numbers
Conditional Compilation
-
instruction:
#ifdef
、#ifndef
、#if
、#elif
、#else
、#endif
- use: Compile different code segments according to different conditions, which can be used to generate different object codes under different compilation environments or configurations, which is convenient for code porting and debugging, and can also be used to avoid duplicate inclusion of header files, etc.
- Give an example:
#ifdef DEBUG printf("Debugging information: x = %d\n", x); // Compile this statement only when the DEBUG macro is defined#endif #ifndef MY_HEADER_INCLUDED #define MY_HEADER_INCLUDED // Contents of header file#endif #if defined(PLATFORM_WINDOWS) // Windows platform-related code#elif defined(PLATFORM_LINUX) // Linux platform related code#else // Code for other platforms#endif
Cancel macro definition
-
instruction:
#undef
- use: Cancel the previously defined macros and use them when you need to redefine the macros or avoid macro conflicts.
- Give an example:
#define FOO 100 // Some codes that use FOO#undef FOO #define FOO 200 // Redefine FOO
Other compilation controls
-
instruction:
#pragma
-
use: Provide specific compilation instructions to the compiler, different compiler pairs
#pragma
The support and specific usage are different, common ones such as setting the compiler's warning level, controlling the alignment of the code, etc. - Give an example:
#pragma warning(disable:4996) // Close the compiler's prompt for warning No. 4996#pragma pack(push, 1) // Set the structure to align it by 1 bytestruct MyStruct { char a; int b; }; #pragma pack(pop) // Restore default alignment
This article about what are the preprocessor instructions in C/C++ and what are their uses. For more related C++ preprocessor instructions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!