Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the preprocessing effect in C language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to achieve the preprocessing effect in C language. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Preface

Compiling a C language program involves many steps. The first step is called preprocessing. The preprocessor of C language performs some textual operations on the source code before it is compiled. Its main tasks include deleting comments, inserting file contents contained in the # include directive, defining and replacing symbols defined by the # define directive, and determining whether parts of the code should be compiled according to some conditional compilation instructions.

I. predefined symbols

The following table shows the symbols defined by the C language preprocessor. Their values range from string constants to decimal numeric constants.

Symbol sample value meaning _ _ FILE__ "test.c" current compiled source file name _ _ LINE__25 this file current line number _ _ DATE__ "Dec 27 2021" file compilation date _ _ TIME__ "21:30:23" file compilation time _ _ STDC__1 if the compiler complies with ANSI C, the value is 1, otherwise two and # define are not defined

Let's take a look at its usage first.

# define name stuff

With this instruction, whenever a signed name appears after the instruction, the preprocessor replaces it with stuff.

If the stuff in the definition is very long, you can divide it into several lines, with a backslash at the end of each line except the last line, as shown in the following example:

# define DEBUG_PRINT printf ("File% s line% d:"\ "x =% d, y =% d, z =% d,\ _ _ FILE__, _ _ LINE__, x, y, z)

A feature is taken advantage of here: adjacent string constants are automatically concatenated into a string. This type of declaration is useful when debugging a program that has many different calculations involving a set of variables. We can easily insert a test statement to print out their current values.

X * = 2th y + = x TX z = x * y th DEBUGUGUG PRINTITE. Macro

The # define mechanism includes a provision that allows parameters to be replaced into text, which is often referred to as a macro or define macro. Here is how macros are declared:

# define name (parameter-list) stuff

Where parameter-list (parameter list) is a comma-separated list of symbols that may appear in stuff. The left parenthesis of the parameter list must be adjacent to the name. Otherwise, the parameter list is interpreted as part of the stuf.

When a macro is called, the name is followed by a comma-separated list of values, each corresponding to a parameter in the macro definition. When parameters appear in the program, the actual values corresponding to each parameter are replaced into stuff.

For example:

# define SQUARE (x) x*xSQUARE (5)

When these two statements are in the program, the preprocessor replaces the following expression with the above expression, which becomes: 5 * 5.

But the above macro exists in a problem, please take a look at the following code:

A = 5printf ("% d\ n", SQUARE (a + 1))

Maybe we intuitively think that this code will print the value of 36. But in fact, it prints 11. Why? Come on, let's make a replacement according to the rules of the macro, and this statement will become:

Printf ("% d\ n", a + 1 * a + 1)

Did you find the problem? the expressions generated by substitution here are not evaluated in the desired order. So, we need to parenthesize the parameters defined by the macro, including the stuff as a whole. This will produce the results we expect.

There are several steps involved in extending # define definition symbols and macros in your program.

1. When you call a macro, first check the parameters to see if they contain any symbols defined by # define. If they exist, they will be replaced first.

two。 The replacement text is then inserted into the location of the original text in the program. For macros, parameter names are replaced by their values.

3. Finally, the talent scans the resulting text to see if it contains any symbols defined by # define. If so, repeat the above process.

two。 Macros and functions

Macros are used very frequently to perform simple calculations, such as finding the larger (or smaller) of the two expressions:

# define MAX (a, b) ((a) > (b)? (a): (B))

It seems that we can also implement this function with functions, so why not use functions? There are two reasons. First of all, the code used to call and return from the function is probably larger than the code that actually performs this small task, so using macros is better than using functions in the program in scale and speed.

Second, and more importantly, the parameter of the function must be declared as a specific type, so it can only be used in expressions of the right type. But macros have nothing to do with type.

There are advantages and disadvantages, compared with using functions, the disadvantage of using macros is that each time you use macros, a copy of the macro definition code will be inserted into the program. Unless macros are very short, using macros can significantly increase the length of your program.

There are also some tasks that cannot be implemented with functions, such as the following code:

# define MALLOC (n, type) ((type*) malloc ((n) * sizeof (type)

Type is a data type, and a function cannot pass a type as an argument.

3. Macro parameters with side effects

When a macro parameter is quarreled once in the macro definition, if this parameter has side effects, it may be dangerous when using the macro, leading to unpredictable consequences. The side effect is that there are permanent consequences when the expression is evaluated. As follows:

X + 1

This expression is the same no matter how many times it is executed, so it has no side effects.

Xerox +

But this expression is different. Each execution changes the value of x, and each execution has a different result. Therefore, this expression has side effects. Let's take a look at the following example, what do you think it will print:

# define MAX (a, b) ((a) > (b)? (a): (B) x = 5 × y = 8 * * z = MAX (x =% d, y =% d, z =% d\ n ", x, y, z)

The result is: X = 6, y = 10, z = 9. The reason for this result is that the smaller value is increased only once, while the larger value is increased twice-the first time is during comparison and the second time is executed? When the following expression. This is a macro parameter with side effects, which we must pay attention to when using it.

4. The difference between macros and functions

To analyze through a table:

Attribute # define macro function code length is inserted into the program each time the macro code is used. Except for very small macros, the length of the program will grow dramatically. The function code will only appear in one place each time the function is used. The same code in that place is called faster. The extra overhead operator priority macro parameters that function calls and returns are evaluated in the context of all surrounding expressions, unless they are parenthesized. Otherwise, the priority of the adjacent operator may change. The function parameter is evaluated once when the function is called, and the result is passed to the function. It is easier to predict that the parameter evaluation parameters will be re-evaluated each time they are used in the macro definition. Due to multiple evaluations, parameters with side effects may have unpredictable consequences. Parameters are only evaluated once before the function is called, and the repeated use of parameters in the function will not lead to multiple job search processes. The side effects of parameters do not cause any special problems. Parameter type macros are type independent. As long as the operation on the parameter is legal, it can use any type of parameter function whose parameters are type-dependent, and if the parameters are of different types, they need to use different functions, even if they perform the same 5.#undef.

# undef this preprocessing directive is used to remove a macro definition:

# undef name

If an existing name needs to be redefined, its old definition must first be removed with # undef.

III. Conditional compilation

When compiling a program, it will bring us great convenience if we can translate or ignore a selected statement or a group of statements. Conditional compilation (conditional compilation) can do this. With conditional compilation, you can choose whether part of the code is compiled normally or ignored completely. The basic structures used to support conditional compilation are # if directives and # endif directives. Here is how it is used:

# if constant-expression statements#endif#if constant-expression statements#elif constant-expression other statements#else other statements#endif

At the same time, another use of conditional compilation is to select different parts of the code at compile time. So the # if instruction also has optional # elif and # else clauses. As follows:

# if constant-expression statements#elif constant-expression other statements#else other statements#endif

The number of times the # elif clause appears can be unlimited. But each constant expression (constant-expression) is compiled only if the values of all previous constant expressions are false. Statements in the # else clause are compiled only if the values of all previous constant expressions are false.

IV. The file contains

The # include directive causes the contents of another file to be compiled as if it were actually where the # include directive appears. This replacement is performed in a simple way: the preprocessor deletes the instruction and replaces it with the contents of the containing file. If a header file is included in ten source files, it is actually compiled ten times.

1. The function library file contains

The C language compiler supports two different types of # include files: library files and local files. In fact, there is little difference between them.

The library file is included using the following syntax:

# include

There are no restrictions on filename (file name), but according to regulations, standard library files end with an .h suffix.

The compiler looks for the function library header file by observing the "series of standard locations" defined by the compiler. The compiler documentation you use will explain where these standards are located and how to modify them or add other locations to the list.

two。 The local file contains

Here is another form of the # include directive:

# include "filename"

The standard allows the compiler to decide whether to treat # include in native form differently from # include in library form. You can first use a special way to deal with the local header files, and if it fails, the compiler will deal with them in the same way as the library header files.

A common strategy for dealing with local header files is to look in the current directory where the source file is located, and if the header file is not found, the compiler looks for the local header file in the standard location just like the function library header file.

This is the end of this article on "how to achieve preprocessing effect in C language". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report