当前位置:网站首页>Details of C language compilation preprocessing and comparison of macros and functions
Details of C language compilation preprocessing and comparison of macros and functions
2022-07-25 02:19:00 【JDSZGLLL】
Catalog
5. Macro and function comparison
introduction
We have a certain understanding of the compilation process , For the general process, please refer to the following figure :

Predefined symbols
__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 #include<stdio.h>
#include<windows.h>
int main()
{
printf("file:%s line:%d date%s time:%s\n", __FILE__, __LINE__, __DATE__, __TIME__);
Sleep(10000);
printf("file:%s line:%d date%s time:%s\n", __FILE__, __LINE__, __DATE__, __TIME__);
return 0;
}The operation results are as follows :

You can know , Predefined symbols are used to record information during compilation , It will not change during execution .
#define
#define It does two things :
1. Define identifier
#define MAX 1000
#define reg register // by register This keyword , Create a short name 2. Defining macro
#define The mechanism includes a provision , Allow parameters to be replaced with text , This implementation is often called a macro (macro) Or the definition
macro (define macro).
#define SQUARE(x) x * xWhether defining identifiers or macros , Is a replacement process , Only macros pass parameters .
3.#define Replacement rules
Extend... In a program #define When defining symbols and macros , There are several steps involved :
1. When calling a macro , First, check the parameters , See if it contains any information from #define Defined symbols . If it is , They are replaced first .
2. 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 .
3. Last , Scan the result file again , See if it contains any information from #define Defined symbols . If it is , Repeat the above process .
4 # and ##
int i = 10;
#define PRINT(FORMAT, VALUE)\
printf("the value of " #VALUE "is "FORMAT "\n", VALUE);
PRINT("%d", i+3);// What effect has it produced ?Output is :
the value of i+3 is 13
You can see that #VALUE You can put VALUE The contents in are retained as strings , Without conversion .
## You can combine the symbols on both sides of it into one symbol .
It allows macro definitions to create identifiers from detached pieces of text .
#define ADD_TO_SUM(num, value) \
sum##num += value;
...
ADD_TO_SUM(5, 10);// Role is : to sum5 increase 10.5. Macro and function comparison
| Belong to sex | #define Defining macro | function |
| generation code Long degree | Every time I use it , Macro code is inserted into the program . Except very Beyond small macros , The length of the program will increase significantly | Function code only appears in one place ; Every time The first time you use this function , Call that The same code in place |
| Of board That's ok speed degree | faster | There is an extra opening for the call and return of the function pin , 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 , So there are side effects The evaluation of parameters used 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 , It needs to be different Function of , Even if their task is Different . |
| transfer try | Macros are inconvenient to debug | Functions can be debugged statement by statement |
| Deliver return | Macros cannot be recursive | Functions can be recursive |
In short , Macros are more flexible than functions .
Conditional compilation
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
#endifFile contains
The header file will expand after preprocessing , In order to prevent space waste , To prevent multiple references to header files , There are two ways :
#ifndef __HEAD_H__
#define __HEAD_H__
......
......
#endifas well as
#pragma once
边栏推荐
- On the economic model of open source ecology
- Using the artifact typora+picgo, Youdao cloud can automatically upload pictures in markdown without members
- Fraud detection using CSP
- Please ask a question: how to set the new table of MySQL CDC 2.2.x to only receive increment
- Arthas case: dynamic update application logger level
- Jsonp solves cross domain plug-ins (JS, TS)
- Interpretation of video generation paper of fed shot video to video (neurips 2019)
- Point to point copy and paste of web pages
- Project management tool Zen
- Example demonstration of "uncover the secrets of asp.net core 6 framework" [02]: application development based on routing, MVC and grpc
猜你喜欢

How can arm access the Internet through a laptop?

Inventory of well-known source code mall systems at home and abroad

1260. Two dimensional grid migration: simple construction simulation problem

JVM Foundation

iptables :chains, target

Nacos service discovery data model

Apk packaging process

Fraud detection using CSP

Solution to the occupation of project startup port

Peripherals: interrupt system of keys and CPU
随机推荐
Using ODBC to consume SAP ABAP CDs view in Excel
Agreement on sharing agricultural scientific data in China
Query the thread information of MySQL server (detailed explanation)
Data management process model of science and technology planning project
A weird jedisconnectionexception: connection rejected problem
After six years of precipitation, new consumption has found a digital transformation paradigm
Freedom and self action Hegel
Digital business cloud: how to realize the application value of supplier SRM management system?
Chinese son-in-law OTA Ono became the first Asian president of the University of Michigan, with an annual salary of more than 6.5 million!
Fraud detection using CSP
It's still a synchronization problem
Mobile Robotics (3) Kalman filter
iptables :chains, target
Google launched another "man grabbing war" for core making, and Intel's 17 year veteran joined!
Four redis cluster schemes you must know and their advantages and disadvantages
Scalar, vector, matrix calculus
Jsonp solves cross domain plug-ins (JS, TS)
Summary thinking caused by the function of a SMS verification code [easy to understand]
PostgreSQL views tables, table indexes, views, table structures, and parameter settings
C#/VB. Net insert watermark in word