Use C macro

Source: Internet
Author: User


C1 condition include

As follows:

Code

# Ifndef main_h _

# Define main_h _

Other content

# Endif


When we see the header file, the function is to prevent this header file from being included multiple times.

Repeated definitions occur when multiple include operations are performed. Therefore, you must use this definition in each header file.

If you still don't know how to use it, you can see the standard header file of C, such as fcntl. h.


2. Conditional compilation

As follows:

Code

# Ifdef _ debug

Printf ("This debug info/N ");

# Endif


If the _ debug macro is not defined, the above line will not be compiled.

However, after _ debug is defined, the above line will be compiled to write a simple program for testing.

Code

# Include <stdio. h>

Int main ()

{

# Ifdef _ debug

Printf ("Hello World/N ");

# Else

Printf ("No debug ");

# Endif

Return 0;

}


First use gcc-d_debug main. c

Second use of GCC main. c

View the result of running twice

3. Define a value so that you do not need to modify the code elsewhere when modifying the value later. You only need to modify the macro definition.

For example, a multi-language version of a software.

As follows:


Code

# Include <stdio. h>

# Define print_str "Hello dd"

Main (){

Printf (print_str );

Return 0;

}


During compilation, print_str is replaced with "Hello dd"

It will be convenient to modify later


It can also be defined as a function.

# Include <stdio. h>

# Ifdef _ debug

# Define a (x) A (x)

# Else

# Define a (x) B (X)

# Endif

Int A (int x)

{

Return x + 1;

}

Int B (INT X ){

Return x + 100;

}

Int main (){

Printf ("A (10) value is % d", a (10 ));

Return 0;

}

It can also be defined

# Define a

Of

However, after being defined as a (x), only a compiler with the (x) type after a performs replacement. it is safer to replace only functions instead of variables.


Fourth

Variable Parameter macro

Sometimes it is necessary to define a macro to replace a function, but this function is a variable parameter.

The definition method is as follows:

Code

# Define print (...) printf (_ va_args __)

# Include <stdio. h>

Int main (){

Print ("% d % S % s", 1, "Have you eaten? Smile mm :)", "/N ");

Return 0;

}


Fifth macro combination

That is, the usage of ##and #

# Connect two macros with a symbolic connection

# Replace the name with a string

As follows:

Code

# Define s5 (a) supper _ #

# Include <stdio. h>

Void supper_printf (const char * P)

{

Printf ("This Is supper printf:/n % s/n", );

}

Int main ()

{

S5 (printf) ("Hello owrld ");

Return 0;

}


# Usage:

# Include <stdio. h>

# Define s (P) # P

Int main (){

Printf (S (p) "/N ");

Return 0;

}

Run it.

The macro definition concept found on the internet is attached.

Article 1

Chapter 9 preprocessing commands

Concept of preprocessing: processing before Compilation

The Preprocessing of C has three main aspects: macro definition, file inclusion, and Conditional compilation.

The pre-processing command starts with the symbol.

9.1 macro definition

9.1.1 macro definition without Parameters

Macro definition is also called macro replacement and macro replacement"

Format:

# Define identifier string

The identifier is a symbolic constant, also known as a macro name"

Preprocessing (pre-compilation) is also called macro expansion: replacing macro names with strings.

The key to understanding the concept of "macro" is "change ". Everything needs to be changed on the premise that everything is changed. before doing anything, you must change everything ".

That is to say, we need to change the meaning and functions of related commands or statements before making a specific analysis. "If you do not care about the meaning and functions of these commands, you must change them first ".

The remaining problems are simple:

1. Who should be replaced? 2. What should I change?

# Define PI 3.1415926

Replace all PI in the program with 3.1415926

Li9_1.c

Note: (1) macro names are generally capitalized.

(2) using macros can improve the versatility and accessibility of the program, reduce inconsistency, reduce input errors, and facilitate modification.

For example, macro definition for array size

(3) preprocessing is performed before compilation, and one of the tasks of compilation is syntax check. Preprocessing does not perform syntax check.

(4) No plus points at the end of the macro definition;

(5) The macro definition is written outside the curly braces of the function, and the scope is the subsequent program, usually at the beginning of the file.

(6) You can use the # UNDEF command to terminate the macro-defined scope.

(7) macro definitions can be nested

Li9_2.c

(8) the string "" Never contains macros

(9) macro definition does not allocate memory, variable definition allocates memory.

9.1.2 macro with Parameters

In addition to replacement of common strings, parameter replacement is also required.

Format:

# Define macro name (parameter table) String

Example: # define s (a, B) a * B

Area = S (3, 2); the first step is changed to Area = A * B; the second step is changed to Area = 3*2;

Similar to function calls, there is a process of integration of dumb and real.

Li9_3.c

(1) If the real parameter is an expression, it is prone to problems.

# Define s? R * R

Area = S (A + B); the first step is changed to Area = r * r; the second step is changed to Area = a + B * A + B;

The correct macro definition is # define s? ? *?

(2) there cannot be spaces between macro names and parameter brackets

(3) macro replacement is only for replacement, without calculation or expression solving

(4) function calls are performed when the program is running after compilation and memory is allocated. Macro replacement is performed before compilation without memory allocation

(5) There is no type or type conversion in the dummy combination of macros.

(6) A function has only one return value. You can use a macro to obtain multiple values.

Li9_4.c

(7) macro expansion makes the source program longer and function calls will not

(8) macro expansion does not occupy the running time, only the Compilation Time, and function calls occupy the running time (memory allocation, field reservation, value transfer, and return value)

Li9_5.c

Analyze"

9.2 "File Inclusion" Processing

One file contains the content of another file

Format:

# Include "file name"

Or

# Include <File Name>

The unit of compilation is to include the processed files. The included files are part of the source files.

Li9_6a.c li9_6b.c

After compilation, only one target file. obj is obtained.

The contained file is also known as the "title file", "header file", and is commonly used as the extension. h.

After the header file is modified, all files containing the file must be re-compiled.

In addition to the function prototype and macro definition, the header file can also have struct definition and global variable definition.

(1) One # include command specifies a header file

(2) If file 1 contains file 2 and file 2 uses file 3, the inclusion command # include of file 3 should be placed on the first line in the header of file 1.

(3) including nesting

(4) <File Name> is a standard method. The system searches for files in the header file directory.

"File name" is first searched in the current directory, and then found in the header file directory

(5) Static global variables in the contained file do not need to be declared in the contained file.

9.3 Conditional compilation

Some statements can be compiled only when the conditions are met.

Format: (1)

# Ifdef identifier

Procedure 1

# Else

Procedure 2

# Endif

Or

# Ifdef

Procedure 1

# Endif

When the identifier has been defined, section 1 is used for compilation.

Format: (2)

# Ifndef identifier

Format: (3)

# If expression

Li9_7.c

Conditional compilation can reduce the target program and shorten the running time.

Pre-compilation increases the number of problem or algorithm solutions, which helps us select the appropriate solution.

Chapter 1 preprocessing procedure

7.1 What Is A Preprocessing Program

A Preprocessing Program is a special statement starting with # at the beginning of a line. For example, # include, # define is a preprocessing statement. Other compilation processes (lexical analysis, syntax analysis, code

Before the statement is generated, optimized, and connected.

The purpose of pre-processing statements is to help programmers compile programs that are easy to read, easy to modify, easy to transplant, and easy to debug. There are four types of pre-processing statements:

Macro definition and macro replacement, file inclusion, Conditional compilation, and row control.

The pre-processing statement is effective from the time it is defined until it is undefined or until it is included in the file knot.


7.2 macro definition and macro replacement


Macro refers to the concept in assembly language. In order to facilitate definition and expansion in C language programs. These statements start with # define and fall into two types: macro definition of symbolic constants and macro definition with parameters.

1. macro definition and macro replacement of symbolic Constants

The macro definition statement of a symbolic constant is in the general format:

# Define identifier string

The identifier is called the macro name.

Note: Do not use '=' between the identifier and string, and do not add ';' at the end ';'.

2. macro definition with parameters and their replacement

A complex macro definition has a parameter list. There are more than one parameter in the parameter list. The general format is as follows:

# Define identifier (parameter list) String

When you replace a macro definition with a parameter, not only do you replace the macro identifier with a string, but you must also replace the parameter.

For example:

# Define Sq (x) * (x ))

Then Sq (A + B) will be replaced by macro (a + B) * (A + B ).

Macro definitions can also be nested, that is, one macro definition can be defined by another macro definition. For example:

# Define Sq (x) * (x ))

# Define cube (x) (Sq (x) * (x ))

3. Macro-defined functions

Macro definition is often used to replace the directly inserted code with functions to improve execution efficiency. Macros of this type are called macro-defined class functions, for example:

# Define min (x, y) (x) <(y ))? (X) :( y ))

With such a macro, you can directly reference it, for example:

M = min (A, B );

This statement is preprocessed:

M = (a) <(B ))? (A) (B ));


7.3 File Inclusion


File Inclusion refers to the inclusion of the content of another definition file in a program file, which is described by the # include statement.

Generally, there are two formats:

(1) # include <File Name>

(2) # include future file name example 〃

First, use angle brackets to find the file under the standard library directory; second, use double quotation marks to indicate that the file is found in the current directory (the directory where the source file is located). If the file cannot be found, go to the standard library directory. Standard System Library

All files are. H files. For example:

# Include <stdio. h>/* Basic constants and macro or function files of standard input and output */

# Include <string. h>/* string function file */

# Include <malloc. h>/* Memory Allocation Function file */

# Include <ctype. h>/* character function file */

# Include <math. h>/* mathematical function library file */

File Inclusion can reduce repetitive work, improve program correctness, and facilitate maintenance and modification. Programmers can put some commonly used symbolic constants, Type Definitions, macro definitions with parameters, and some commonly used self-compiled Functions

In the. h file, use the # include statement to include references.


7.4 Conditional compilation


Conditional compilation measures are provided to allow the same source program to generate different directory codes based on different compilation conditions (parameters), which facilitates debugging and porting.

Conditional compilation control statements have different forms, which are discussed below.

1. # ifdef statement and Its Usage

General format:

# Ifdef identifier

Statement Block 1

# Else

Statement Block 2

# Endif


7.4 format input/output

The formatted console I/O functions are related to the standard I/O library. The source program should start with a standard input/output header file:

# Include <stdio. h>

1. printf ()

The printf () function Outputs Various basic types of data in the specified format. The general format is as follows:

Printf ("control string", parameter list)

The control string consists of two parts: the character to be displayed and the format string. The format string starts with "%", followed by the format code. The format string corresponds to the parameter one by one.

2. scanf ()

Scanf () is used to read various types of data and automatically convert it to an appropriate format. The general format is scanf ("control string", parameter list)

The control string is similar to the control string in printf (). It also contains a format string consisting of a format code starting with "%. The parameter list lists the addresses of variables rather than the names of variables.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.