当前位置:网站首页>C language preprocessing instructions - learning 21
C language preprocessing instructions - learning 21
2022-06-12 00:38:00 【XG. Solitary dream】
This paper is finally updated at 2022 year 02 month 15 Japan , Has more than 12 I didn't update it . If the article content or picture resources fail , Please leave a message for feedback , I will deal with it in time , thank you !
Overview of preprocessing commands
- So-called Compile preprocessing Is in the compiler to C Before compiling the source program , from Compile preprocessor For these Compile the preprocessing instruction line for processing The process of .
- C In language , With “#” Beginning line , All called Compile preprocessing instruction line , End of each line No, “;” .
- C The preprocessing functions provided mainly include the following 3 Kind of :
- Macro definition
- File contains
- Conditional compilation
Macro definition
No parameter macro
- Definition format of parameterless macro :
#defineidentifiercharacter stringdefineDefine commands for macros .identifierIs the macro name of the specified document , Usually in capital letters , To distinguish it from variables .character stringIt can be a constant 、 Expression etc. .
- for example :
#define PAI 3.1415926
- “ macro ”: Use one identifier To represent a character string .
- “ Macro name ”: Is defined as “ macro ” Of identifier .
- “ Macro replace ”: During compilation preprocessing , The preprocessor converts all occurrences in the program “ Macro name ”, Use both Replace the string in the macro definition . After completion , Then the program is handed over to the compiler for processing .
- Advantages of using macro definitions :
- It can improve the maintainability of the source program ;
- It can improve the portability of the source program ;
- Reduce the workload of writing string repeatedly in the source program .
- A few notes about macro definitions :
- Macro name It's usually used Capital Express , To show the difference from variables . But this It's not a grammatical rule .
- Macro definition is not C sentence , therefore You cannot add a semicolon at the end of a line .
- When the macro is expanded , The preprocessor is defined only by macro Simply replace the macro name , Without any inspection .
- Macro definition command #define appear Outside the function , The valid range of macro names is : After defining the command , By the end of this document .
- In macro definition , You can refer to the defined macro name .
- for example :
# defineR 3# define PI 3.14159# define S PI*R*R
- For characters in a string enclosed in double quotation marks , Even if it has the same name as the macro name , No macro expansion .
- for example :
printf("R=%f,S=%f",R,S)
- for example :
- Symbolic constant
- When defining a parameterless macro , If... In the macro definition “ character string ” It's a Constant , The corresponding ““ Macro name ” be called “ Symbolic constant ”.
- Example :
#include<stdio.h>
#define A 1+2 // There are no brackets
void main() {
int a;
a = A * 2; // After replacement a = 1+ 2 * 2 therefore a = 5
printf("a = %d,A = %d\n", a, A);
}Have reference macro
- Definition format of macro with parameters :
#defineMacro name ( Parameter table )character string
- for example :
#defineADD(X,Y)(X+Y)
- There are macro calls and macro expansions
- Invocation format :
Macro name ( Argument table ) - Macro expansion : Use the argument string provided by the macro call , Directly replace the corresponding formal parameter string in the macro definition command line , Nonparametric characters remain unchanged .
- Invocation format :
- Example :
#include<stdio.h>
#define PAI 3.1415926
#define S(r) PAI*(r)*(r)
void main() {
double a;
printf(" Please enter the radius :\n");
scanf_s("%lf", &a);
printf(" The radius is %.2f Area of circle :%.2f\n", a, S(a));
}- A few notes about the macro with parameters :
- 1. When defining a macro with parameters , There must be no space between the macro name and the left parenthesis .
#defineS(r)PAI*(r)*(r)- In the example above S and (r) Between , You can't have Spaces . If it's written
#defineS(r)PAI*(r)*(r) - Express Macro name S The replaced string is
(r) PAI*(r)*(r).
- 2. There are parameters in the macro definition , Formal parameters do not allocate memory units , Therefore, formal parameters do not have to be typed ; and The arguments in the macro substitution have specific values We should use them to replace formal parameters , therefore Arguments must be typed .
- In a macro with parameters , Just symbol substitution .
- 3. When calling a macro with a parameter name , A pair of parentheses is essential , In parentheses The number of arguments should be the same as the number of formal parameters , If you have more than one parameter , Parameters are separated by commas .
- 4. stay Macro definition Medium Formal parameters are identifiers , and Macro call Medium Arguments can be expressions . Macro replacement Replace the actual parameter expression as is without calculation .
- 5. In the macro definition , In the string Formal parameters and the entire expression are usually enclosed in parentheses To avoid mistakes .
- Example :
# include< stdio.h >
# define A(X,Y) X*Y
void main()
{
int a, s;
float w;
printf(" Please enter a Value :\n");
scanf_s("%d", &a);
s = A(a, a + 1);
w = 6 / A(a, a);
printf("s = a*a+1 = %d,w = 6/a*a = %.2f\n", s, w);
}- Written as follows :
#defineA(X,Y)(X)*(Y) - The first 1 Macro calculation is called times s When the value of , Statement after macro replacement :
s = ((a)*(a+1)); - The first 2 The number of calls is calculated w When the value of , Statement after macro replacement :
w = 6/((a)*(a)); - The result is
s = ((a)*(a+1)) = 42, w = 6/((a)*(a))= 6.00 - When defining a macro, parentheses should be added to both sides of the parameter , Parentheses should also be added to the entire string .
File contains
- File inclusion means that in a file , To include the entire contents of another file . C Language use #include The directive implements the functions contained in the file .
- The file contains the syntax format :
- First, look for the header file under the current directory of the source code , This method is usually used to include self-defined header files .
#include" file name " - First, in the compiler default include Find the header file in the directory , This method is usually used to include standard library header files .
#include< file name >
- First, look for the header file under the current directory of the source code , This method is usually used to include self-defined header files .
- for example :
#include<stdio.h>#include<math.h>#include"diy.h"
- In the compilation preprocessing phase , The preprocessor will replace this line with the contents of the specified file . Thus, the specified file and the current source program file are connected into a source file .
- If the program is big , best Divided into several different files , Each file contains a set of functions . These documents are for #include Include them at the beginning of the main program .
- There are some functions and macros that are used in almost all programs . You can put these Common functions and macro definitions are stored in one file , Include this file in the program you write , The contents of this file are inserted into the program .
- The included file extension can be
.h, This extension is The header file . It is usually included in the head of the program . - All library functions are divided into different categories , Stored in different files .
- Note the following points when using the file include command :
- 1. When the included file is modified , The source program containing this file must be recompiled and connected .
- 2. A file include command can only specify one included file , If you want to include multiple files , Then multiple files should be used to contain commands .
#include<stdio.h>#include<string.h>#include<math.h>
- 3. File contains allow nesting , That is, one included file can contain another file .
- During compilation preprocessing , Right #include Command to ” File contains ” Handle , take f2.c Of Insert all contents To #include"f2.c" Command in , The results shown . At compile time , Yes f1.c Compile as a source file unit .
Conditional compilation
- If you want a part of the program to compile only when certain conditions are met , That is, specify the compilation conditions for this part , You can use conditional compilation to implement .
- Conditional compilation has the following forms :
- Form 1
#ifdef identifier
Procedures section 1
#else
Procedures section 2
#endif
// perhaps
#ifdef identifier
Procedures section 1
#endif- function : If the identifier is Macro defined directive Defined macro name , Only for program segments 1 Compile , Procedures section 2 Do not participate in compilation ; Otherwise, only for program segments 2 Compile , Procedures section 1 Do not participate in compilation .
- Form 2
#ifndef identifier // if n def
Procedures section 1
#else
Procedures section 2
#endif- function : If the identifier is Instructions not defined by macros Defined macro name , Only for program segments 1 Compile , Procedures section 2 Do not participate in compilation ; Otherwise, only for program segments 2 Compile , Procedures section 1 Do not participate in compilation . Contrary to form one .
- Form 3
#if Constant expression
Procedures section 1
#else
Procedures section 2
#endif- function : For example, the value of a constant expression is really ( Not 0), For program segments 1 Compile , Otherwise, for program segments 2 Compile . Therefore, the program can be made under different conditions , Complete different functions .
- Example
#include <stdio.h>
#define DEBUG 0
void main()
{
#if DEBUG
printf("Debugging...\n");
#else
printf("Running...\n");
#endif
}#define DEBUG 1
- Of course, the conditional compilation described above can also be realized by conditional statements . But using conditional statements will compile the whole source program , The generated object code program is very long ;
- And conditional compilation , Then only the program segments are compiled according to the conditions 1 Or program segment 2, The generated target program is shorter . If the program segment selected by the condition is very long , The method of conditional compilation is very necessary .
- It is conducive to the portability of the program , Increase the flexibility of the program .
边栏推荐
- Industrial control system ICs
- 时间选择器样式错乱 中间文字被遮挡
- Global and Chinese chromatographic silica gel resin industry research and investment direction forecast report 2022 Edition
- 模块八-设计消息队列存储消息数据的 MySQL 表格
- How to optimize plantuml flow diagram (sequence diagram)
- 2022 Tibet latest special worker (construction elevator) simulation test question bank and answers
- DPT-FSNET: DUAL-PATH TRANSFORMER BASED FULL-BAND AND SUB-BAND FUSION NETWORK FOR SPEECH ENHANCEMENT
- The long polling processing mechanism of the service end of the # yyds dry goods inventory # Nacos configuration center
- DevOps落地实践点滴和踩坑记录-(1)
- Adult education online training website open source
猜你喜欢

汛期化工和危险品企业如何加强防控重大安全风险

2023 spring recruit | ant group middleware Intern Recruitment

Industrial control system ICs

IP addressing overview

Optimization method of win7 FPS

月份选择器禁用当月以后的数据 包含当月

一、Flutter 入门学习写一简单客户端

WPS标题段前间距设置无效解决方案

win10文件夹状态红叉表示的是什么

How to strengthen the prevention and control of major safety risks for chemical and dangerous goods enterprises in flood season
随机推荐
Motianlun domestic database salon | Xu Li: Alibaba cloud's native lindorm TSDB database drives the upgrading of industrial it & ot hyper integrated digital system
Detailed explanation of merge sorting
模块八-设计消息队列存储消息数据的 MySQL 表格
How to change the font size of Apple phone WPS
gin集成图形验证码
Global and Chinese chromatographic silica gel resin industry research and investment direction forecast report 2022 Edition
Redis advanced - correspondence between object and code base
UVM: transaction level modeling (TLM) 1.0 communication standard
設計消息隊列存儲消息數據的 MySQL 錶格
Started with trust and loyal to profession | datapipeline received a thank you letter from Shandong city commercial bank Alliance
详解异步任务:函数计算的任务触发去重
KV storage separation principle and performance evaluation of nebula graph
Enterprise wechat H5_ Integrated message decryption class, message push get and post callback processing
Adult education online training website open source
What does the Red Cross of win10 folder status indicate
Cuiyunkai, CEO of Gewu titanium Intelligent Technology: data value jump, insight into the next generation of change forces
基于.NetCore开发博客项目 StarBlog - (11) 实现访问统计
验证码是自动化的天敌?看看阿里P7大神是怎么解决的
Experiment 6 constructor + copy construction
How to make scripts executable anywhere