当前位置:网站首页>[C language] preprocessing details
[C language] preprocessing details
2022-07-24 02:18:00 【Life is made by oneself ~】
precompile
One 、 Program translation environment and execution environment
1.1 Translation environment
C Each time the language runs a program, an executable program will appear .exe file , So how did this start .c File becomes .exe What about the documents ?
1️⃣ All source files ( The header file will be copied to the source file ) Convert to object file by compiler (.obj)
2️⃣ Object files are combined by linkers , Form an executable program

And here the compiler handles The build process It can also be divided into three parts :
1.2 Preprocessing -> compile -> assembly -> link
Preprocessing :
1️⃣ Include header file
2️⃣ Macro replace
3️⃣ To comment on
test.c -> test.i
compile :
1️⃣ hold C Convert language code into assembly code
2️⃣ the Syntax analysis , Lexical analysis , Semantic analysis , Symbol summary ( Global symbols such as main function 、 Function name )
test.i -> test.s
assembly :
1️⃣ Convert assembly code into Binary instructions
2️⃣ Form a symbol table ( Function name plus address )
test.s -> test.o
link :
1️⃣ Merge segment tables ( Merge the same content into one area )
2️⃣ Merging and relocating symbol tables ( The address at the declaration is meaningless , Merge and choose meaningful )
test.o -> text.exe
1.3 Running environment
The process of program execution :
1) Procedure must Load into memory . In an operating system environment : This is usually done by the operating system . In an independent environment , The loading of the program must be arranged manually , It can also be done by putting executable code into read-only memory .
2) The execution of the procedure begins . And then I call main function .
3) Start executing program code . At this point, the program will use a runtime stack (stack), Store function local variables and return address . Programs can also use static (static) Memory , Variables stored in static memory retain their values throughout the execution of the program .
4) To terminate the program . Normal termination main function ; It could be an accidental termination .
Two 、 Detailed pretreatment
2.1 Predefined symbols
C Language provides some symbols that can be used directly :
__FILE__ // Source files to compile
__LINE__ // The current line number of the file
__DATE__ // The date the file was compiled
__TIME__ // When the file was compiled
__STDC__ // If the compiler follows ANSI C, Its value is 1, Otherwise, it is not defined
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
return EXIT_FAILURE;
}
for (int i = 0; i < 5; i++)
{
fprintf(pf, "file:%s line:%d date:%s time:%s\n", __FILE__, __LINE__, __DATE__, __TIME__);
}
fclose(pf);
pf = NULL;
return 0;
}

2.2 #define
grammar :
#define name stuff
#define MAX 100
#define STR "abc"
int main()
{
printf("%d %s", MAX, STR);
return 0;
}
After pretreatment :
int main()
{
printf("%d %s", 100, "abc");
return 0;
}
#define Don't add ;
Endurance :
#define DEBUG_PRINT printf("file:%s\tline:%d\t \ date:%s\ttime:%s\n" ,\ __FILE__,__LINE__ , \ __DATE__,__TIME__ )
2.3.1 #define Defining macro
#define name( parament-list ) stuff
For example, now realize a macro of square :
#define SQUARE( x ) ((x) * (x))
int main()
{
printf("%d", SQUARE(5));
return 0;
}
Because macros replace code directly , So in some cases, there will be symbol priority problems , So we should try to add more parentheses .
2.3.2 #define Replacement rules
Extend... In a program #define When defining symbols and macros , There are several steps involved .
- When calling a macro , First, check the parameters , See if it contains any information from #define Defined symbols . If it is , They first
Be replaced .- The replacement text is then inserted into the program at the location of the original text . For macros , Parameter names are replaced by their values .
- Last , Scan the result file again , See if it contains any information from #define Defined symbols . If it is , Just repeat
Describe the process .
Be careful :
1. Macro parameters and #define Other... Can appear in the definition #define Defined symbols . But for macros , No recursion .
2. When the preprocessor searches #define When defining symbols , The contents of string constants are not searched .
2.3.3 # and ##
#:
Write the parameter into the string
#define PRINT(n) printf("the value of " #n " is %d\n", n)
int main()
{
int n = 10;
PRINT(n);
return 0;
}

#n It will translate into "n".
##:
Merge symbols
#define CAT(a, b) a##b
int main()
{
printf("%s\n", CAT("abc", "def"));
int ABC = 1;
printf("%d\n", CAT(A, BC));
return 0;
}

2.3.4 Macros with side effects
#define MAX(a, b) (a) > (b) ? (a) : (b)
int main()
{
int a = 5;
int b = 4;
int m = MAX(a++, b++);
printf("%d\n", m);
printf("%d %d", a, b);
return 0;
}
result :
6
7 5
The original intention is to seek a larger value , This double counting is a side effect .
2.3.5 Macros and functions
Compare the size of macros and functions :
#define MAX(a, b) a > b ? a : b
int Max(int a, int b)
{
return (a > b ? a : b);
}
The advantages of macro :
1️⃣ Function must declare type , Macros don't , Macros are type independent .
2️⃣ Macros are more efficient than functions , Because the function needs to create stack frames and pass parameters .
The disadvantages of macro :
1) Every time you use a macro , A macro defined code will be inserted into the program . Unless the macro is short , Otherwise, the length of the program may be greatly increased .
2) Macros can't be debugged .
3) Macro is type independent , It's not rigorous enough .
4) Macros can cause operator priority problems , It is easy for Cheng to make mistakes .
2.3 #undef
This instruction is used for Remove a macro definition .
#define MAX 100
int main()
{
#undef MAX
MAX;//error
return 0;
}
2.4 Conditional compilation
When compiling a program, if we want to translate a statement ( A set of statements ) It's convenient to compile or discard . Because we have conditional compilation instructions .
#define __DEBUG__
int main()
{
int i = 0;
int arr[10] = {
0 };
for (i = 0; i < 10; i++)
{
arr[i] = i;
#ifdef __DEBUG__
printf("%d\n", arr[i]);// To see if the array assignment is successful .
#endif //__DEBUG__
}
return 0;
}
If the conditions are met, let printf() Participate in compiling , If you are not satisfied, you will not participate in compilation .
int main()
{
#if 0
printf("abc");
#endif
return 0;
}
Conditional compilation of multiple branches :
#define M 3
int main()
{
#if M < 5
printf("<");
#elif M == 5
printf("==");
#else
printf(">");
#endif
return 0;
}
Judge whether it is defined :
#define A 1
int main()
{
#if defined (A)
//#ifdef A
//#if !defined(A)
//#ifndef A
printf("YES");
#endif
return 0;
}
2.5 File contains
In order to prevent the file from being included repeatedly :
#ifndef __TEST_H__
#define __TEST_H__
.....
#endif
边栏推荐
- [MySQL] character set utf8mb4 cannot store the record of expression stepping on the pit
- 暗黑系王者,低照度图像增强技术解析
- College degree want to 0 basic programming after looking for a job feasible?
- NetApp FAS系列一个CIFS bug引起的控制器重启案例分享
- Ggplot2 displays png
- MySQL---four JDBC
- Mysql database UDF authorization learning
- Combined with actual combat, analyze gb/t 28181 (II) -- equipment directory synchronization
- Installation, configuration and use of sentry
- 什么叫裸写SQL?express操作mysql用什么中件间或插件好呢?
猜你喜欢

2022.7.22 JS entry common data types and methods

View binding confusion. I have been studying confusion for two days.

LeetCode 70爬楼梯、199二叉树的右视图、232用栈实现队列、143重排链表

Local empowerment learning

Distributed resource management and task scheduling framework yarn

pbootcms模板调用标签序数从2开始或者自动数开始

ASP. Net core write a cache attribute tool

Deliver temperature with science and technology, vivo protects the beauty of biodiversity

Precautions for using XXL job

【MySQL】字符集utf8mb4无法存储表情踩坑记录
随机推荐
Build a CPU Simulator
分布式资源管理与任务调度框架Yarn
Where is the safest place to open a futures account now with the lowest handling fee?
快速排序注意点
Excel simple macro
How CAD draws arrows with arcs
氢能创业大赛 | 国华投资董事长刘小奇:发挥风光氢储融一体化优势 高水平承办创业大赛
Notes - record the solution to the failure of @refreshscope dynamic refresh configuration
Reconnaître le Protocole de couche de transport - TCP / UDP
[important notice] the third phase of planet online training is coming! Explain how to build your own quantitative strategy on qtyx
Distributed resource management and task scheduling framework yarn
Install go environment under Kali
BPG笔记(三)
Summary of the first change to open source middleware keycloak
Structure the second operation of the actual combat battalion module
The communication principle between native components, applets and clients, and the operation principle of video, map, canvas, picker, etc
Seatunnel architecture
Study and use of burpsuite plug-in
Chapter 9.2 program control of MATLAB
Ora-12899 error caused by nchar character