当前位置:网站首页>[C language] program environment and preprocessing
[C language] program environment and preprocessing
2022-07-23 19:16:00 【Jiang Lingyu's daily account】


One 、 Common programming errors
Two 、 The translation environment and running environment of the program
6、 Advantages and disadvantages of macros and functions
Four 、 Conditional compilation instructions
Two ways to prevent header files from being included repeatedly
5、 ... and 、 Use <>h and " " Differences between reference header files
6、 ... and 、 Write a macro , Simulation Implementation offsetof
One 、 Common programming errors
1、 Compiler error : Refers to grammatical errors
2、 Linked error : An error occurred during the link , Can't find the symbol or write the wrong name , for example “ Unresolved external symbols ”
3、 Runtime error : The result of running is not what we want
Two 、 The translation environment and running environment of the program
The first 1 One is the translation environment , In this environment, source code is converted into executable machine instructions .
The first 2 One is the execution environment , It's used to actually execute code .
1、 Translation environment

There may be more than one in the source code .c file , Processed by the compiler respectively , Generate respective target files
These object files also need to be combined with system components such as dynamic link library and standard library to generate executable programs , The function of linker is to combine multiple target files and system components
Let's take a closer look at the internal process of compilation and linking , Observe what happens to the file at each step :

1.1 compile
The compilation process is divided into pre compilation ( Preprocessing )、 compile 、 Three steps of assembly
precompile ( Preprocessing ):
The main action of this step :1、 The header file contains 2、define Replace defined symbols and delete macro definitions 3、 Deletion of comments
This step is all text operation
compile :
The main action of this step : hold C Convert language code into assembly code
Symbol summary : The global symbols in each source code are summarized , For example, there are two examples in the figure .s file , Find your own symbol name
assembly :
The main action of this step :1、 Convert assembly code into binary instructions 2、 The symbols summarized in the compilation phase are formed into a symbol table
The symbol table : Match the symbol name with the address
1.2 link
The main action of this step :1、 Merge segment tables 2、 Merging and relocation of symbols
Filter out the address with the correct symbol through the address ( So functions are only declared but not defined , Link error will be reported )
2、 Running environment
1. The program loads 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. Program start execution : 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 or abnormal termination main function
3、 ... and 、 Preprocessing
1、 Built-in symbol
__FILE__ // The path of the source file for compilation
__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 2、define Define identifier
#define MAX 1000// Be careful , When defining identifiers , Don't add a semicolon at the end 3、define Defining macro
#define SQUARE(X) X*X
int main()
{
int m = 5;
int a = SQUARE(m + 1);// Equivalent to 5+1*5+1, be equal to 11
printf("%d",a);
return 0;
}A macro is a replacement , This is equivalent to 5+1*5+1, be equal to 11
If you want the result to be X The square of , Then you need to add a few more parentheses in the macro definition stage
#define SQUARE(X) ((X)*(X))// The outer bracket is also added , If not 10*SQUARE(3) Nor is it the square effect
int main()
{
int m = 5;
int a = SQUARE(m + 1);// Equivalent to (5+1)*(5+1), The result is equal to the 36
printf("%d",a);
return 0;
}4、#define The alternative to
1、 When calling a macro , First, check the parameters , Replace identifier
2、 Text replacement according to the definition of macro
Be careful :
- Macro parameters and #define Other... Can appear in the definition #define Defined symbols . But macro , Not recursive .
- When the preprocessor searches #define When defining symbols , The contents of string constants are not searched .( Symbols with the same macro name in the string will not be replaced )
5、# and ##
1、#

Here, the good string is separated by multiple double quotes , It also features normal printing .
#N Let the compiler know this N Do not replace in the precompile phase
2、##

## Play a connecting role
6、 Advantages and disadvantages of macros and functions
#define Defining macro | function | |
generation code Long degree | Every time I use it , Macro code is inserted into the program . Except for very small macros , The length of the program will increase significantly | Every time you call a function, you use that piece of code |
Of board That's ok speed degree | faster | The call and return of functions require overhead , So it's relatively slow |
fuck do operator optimal First level | Macro parameters are evaluated in the context of all surrounding expressions , Unless you put parentheses , Otherwise, the priority of adjacent operators may produce Unforeseen consequences , Therefore, it is suggested that macros include more when writing Number . | Function parameters are only evaluated when the function is called Value once , Its result value is passed to the function Count . The evaluation result of the expression is easier to predict measuring . |
belt Yes vice do use Of ginseng Count | Parameters may be replaced at multiple locations in the macro body , Therefore, parameter evaluation with side effects may produce unpredictable results . | Function parameters are evaluated only when passing parameters Time , The result is easier to control . |
ginseng Count class type | Macro parameters are type independent , As long as the operation on parameters is legal , It can be used for any parameter type . | The arguments to the function are type dependent , Such as If the type of parameter is different , You need different functions . |
transfer try | Macro cannot be debugged | Functions can be debugged statement by statement |
Deliver return | Macros cannot be recursive | Functions can be recursive |
7、#undef

#undef For cancellation #define The definition of
Four 、 Conditional compilation instructions
1.
#if Constant expression
//...
#endif
// Constant expressions are evaluated by the preprocessor .
Such as :
#define __DEBUG__ 1
#if __DEBUG__
//..
#endif
2. Conditional compilation of multiple branches
#if Constant expression
//...
#elif Constant expression
//...
#else
//...
#endif
3. Judge whether it is defined
#if defined(symbol)
#ifdef symbol
#if !defined(symbol)
#ifndef symbol
4. Nested instruction
#if defined(OS_UNIX)
#ifdef OPTION1
unix_version_option1();
#endif
#ifdef OPTION2
unix_version_option2();
#endif
#elif defined(OS_MSDOS)
#ifdef OPTION2
msdos_version_option2();
#endif
#endifTwo ways to prevent header files from being included repeatedly
#pragma once
#ifndef __TEXT_H__
#define __TEXT_H__
int Add(int a, int b);
#endif5、 ... and 、 Use <>h and " " Differences between reference header files
1、<> How to find it : Go directly to the library directory to find , If you can't find it , Report compilation error
2、"" How to find it : First go to the path where the code is located to find , If you can't find it , Then go to the library directory to find , If you can't find it , Report compilation error
6、 ... and 、 Write a macro , Simulation Implementation offsetof
#include <stdio.h>
#include <stddef.h>
struct S
{
char a;
int b;
char c;
};
#define OFFSETOF(type,member) (size_t)&(((type*)0)->member)
int main()
{
printf("%d\n", OFFSETOF(struct S, a));
printf("%d\n", OFFSETOF(struct S, b));
printf("%d\n", OFFSETOF(struct S, c));
return 0;
}take 0 Convert to structure pointer type , As 0 Offset
The pointer points to the member member
Take out member The address of
Forced to size_t Type to get the structure member relative to 0 Offset at address
6、 ... and 、 Write a macro , The odd and even bits of the binary bits of an integer can be exchanged .
#include <stdio.h>
#define CHANGE(n) ((n&0X55555555)<<1)+((n&0Xaaaaaaaa)>>1)
int main()
{
int m = 0;
scanf("%d", &m);
printf("%d\n", CHANGE(m));
return 0;
}边栏推荐
- Log framework [detailed learning]
- Error "failed to fetch" XXX "temporary failure resolvingw: some index files failed to download" solution
- Multithreading [comprehensive study of graphics and text]
- LeetCode每日一题(1514. Path with Maximum Probability)
- Electronic components - resistance
- Digital security giant entrust revealed that it was attacked by blackmail software gangs in June
- FPGA implementation of IIC bus of IIC protocol (II) (single read / write drive)
- 从txt中读取数据转成yolo格式数据
- DevStack云计算平台快速搭建
- Multithreading & high concurrency (the latest in the whole network: interview questions + map + Notes) the interviewer is calm
猜你喜欢
![[2020] [paper notes] new terahertz detection - Introduction to terahertz characteristics, various terahertz detectors](/img/94/ff67867ef3237d8779628c8872b694.png)
[2020] [paper notes] new terahertz detection - Introduction to terahertz characteristics, various terahertz detectors

【机器学习】吴恩达:终生学习
![[shutter -- layout] flexible layout (flex and expanded)](/img/03/0f07a56487f8e91045f9e893e9f96c.png)
[shutter -- layout] flexible layout (flex and expanded)

Error reporting caused by the use of responsebodyadvice interface and its solution

作为一名后台开发人员,你必须知道的两种过滤器

FPGA implementation of IIC bus of IIC protocol (II) (single read / write drive)

11.神经网络基本概念

数据链路层 -------- 以太网 和 ARP

How can win11 add 3D effects to pictures? Win11 method of adding picture 3D effect

Google正在改进所有产品中的肤色表现 践行“图像公平”理念
随机推荐
How to understand: common code block, construction block, static block? What does it matter?
mBio | 海洋所孙超岷组在深海原位验证了微生物介导的单质硫形成新通路
FPGA实现IIC协议(二)之IIC总线的FPGA实现(单次读写驱动)
ZigBee integrated development environment IAR installation
Rapid establishment of devstack cloud computing platform
1259. Disjoint handshake dynamic programming
What is stack and the difference between stacks
FPGA flash reading and writing based on SPI
[2013] [paper notes] terahertz band nano particle surface enhanced Raman——
树学习总结
FPGA实现IIC协议(一)IIC总线协议
[2022] [paper notes] terahertz quantum well——
Gradle [graphic installation and use demonstration]
Terminal command (all)
Building virtual private network based on softther
Access intranet rds+mysql through SSH
多线程&高并发(全网最新:面试题+导图+笔记)面试手稳心不慌
Perl语言简述
? The problem of front desk parameter transmission needs to be confirmed
[2020] [paper notes] phase change materials and Hypersurfaces——