The preprocessor directive is a command used in C for precompilation processing, and its main functions include header file inclusion, macro definition and conditional compilation. 1. #include is used to introduce header files, standard library use , and customize it with ""; 2. #define defines macros to implement text replacement, and it is recommended to use const or constexpr instead; 3. Conditional compilation controls whether the code segment is compiled through #ifdef, #ifndef, etc.; 4. Others such as #undef cancellation of macros, #pragma sets compilation options, #error triggers errors, etc. Rational use can improve cross-platform compatibility and debugging efficiency, but macro usage should be reduced to enhance code maintainability.
In C, preprocessor directives are part of precompilation processing. They are not real C statements, but commands processed by the preprocessor before compilation. These instructions are usually used in scenarios such as conditional compilation, macro definition, header file inclusion, etc.

#include: Include header file
This is one of the most common preprocessor instructions to insert the contents of a header file into the current source file.
#include <iostream> // Standard library header file#include "myheader.h" // Custom header file
- Use
<...>
to find the header file under the standard library path. - Using
"..."
is to first look up the local directory, and then look up the standard library path. - If you write a custom tool function set, such as
utils.h
andutils.cpp
, you can use#include "utils.h"
to introduce it.
A small suggestion: Avoid repeated including the same header file, you can use Header Guards or #pragma once
.

#define and macro definitions
#define
can be used to define macros, that is, simple text replacement.
#define PI 3.14159 #define SQUARE(x) ((x) * (x))
- Macros are not variables and will not participate in type checking.
- Be careful when using macro functions, so it is recommended to bracket the parameters and the entire expression.
- For example,
SQUARE(ab)
actually expands to(ab) * (ab)
, and an error will occur if there are no brackets.
Although macros are convenient, modern C recommends using const
or constexpr
constants and inline functions instead of macros, which is safer and easier to debug.

Conditional compilation: #ifdef, #ifndef, #else, #endif
These instructions can determine whether to compile a certain piece of code based on certain conditions.
#ifdef DEBUG std::cout << "Debug mode is on." << std::endl; #endif
Common uses:
- Print debugging information in the development stage and will not be enabled after it is launched.
- Cross-platform compatible with code under different systems, such as the APIs of Windows and Linux are different.
For example:
#if defined(_WIN32) // Windows-specific code #elif defined(__linux__) // Linux-specific code #endif
This structure is common in large projects, especially when it is necessary to support multiple operating systems or multiple configurations.
Other common commands
In addition to the above, there are some preprocessor instructions that are not very commonly used but occasionally encountered:
-
#undef
: Undefined a macro. -
#pragma
: Issue some special instructions, such as#pragma once
to avoid repeatedly including header files. -
#error
: Force the compiler to report an error, which is often used for version checking. -
#line
: Modify the current line number, mainly used for debugging or generating code tools.
These are not used much, but are useful in specific scenarios.
Basically that's it. Although the preprocessor instructions are simple, they are very practical in actual development, especially in controlling the compilation process, cross-platform adaptation and debugging. However, it should be noted that you should try to use less macros and use more features of the language itself, so that the code is easier to maintain and understand.
The above is the detailed content of Preprocessor Directives in C. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
