Macro definition skills in C Language

Source: Internet
Author: User

Write a good C language. A beautiful macro definition is very important. Using a macro definition can prevent errors, improve portability, readability, and convenience. The following lists some mature software commonly used macro definitions ......

1. prevent a header file from being repeatedly contained

# Ifndef COMDEF_H

# Define COMDEF_H

// Header file content

# Endif

2. redefine some types to prevent the differences in the number of bytes of the types caused by different platforms and compilers, so as to facilitate migration.
 
Typedef unsigned char boolean;/* Boolean value type .*/

Typedef unsigned long int uint32;/* Unsigned 32 bit value */

Typedef unsigned short uint16;/* Unsigned 16 bit value */

Typedef unsigned char uint8;/* Unsigned 8 bit value */

Typedef signed long int int32;/* Signed 32 bit value */

Typedef signed short int16;/* Signed 16 bit value */

Typedef signed char int8;/* Signed 8 bit value */

// The following is not recommended

Typedef unsigned char byte;/* Unsigned 8 bit value type .*/

Typedef unsigned short word;/* Unsinged 16 bit value type .*/

Typedef unsigned long dword;/* Unsigned 32 bit value type .*/


Typedef unsigned char uint1;/* Unsigned 8 bit value type .*/

Typedef unsigned short uint2;/* Unsigned 16 bit value type .*/

Typedef unsigned long uint4;/* Unsigned 32 bit value type .*/


Typedef signed char int1;/* Signed 8 bit value type .*/

Typedef signed short int2;/* Signed 16 bit value type .*/

Typedef long int int4;/* Signed 32 bit value type .*/


Typedef signed long sint31;/* Signed 32 bit value */

Typedef signed short sint15;/* Signed 16 bit value */

Typedef signed char sint7;/* Signed 8 bit value */


3. Get a byte or word on the specified address.

# Define MEM_ B (x) (* (byte *) (x )))

# Define MEM_W (x) (* (word *) (x )))

4. Calculate the maximum and minimum values.

# Define MAX (x, y) (x)> (y ))? (X): (y ))

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

5. Get the offset of a field in the struct (struct ).

# Define FPOS (type, field )\

/* Lint-e545 */(dword) & (type *) 0)-> field)/* lint + e545 */

6. Obtain the number of bytes occupied by the field in the struct.

# Define FSIZ (type, field) sizeof (type *) 0)-> field)

7. convert two bytes into a Word in LSB format

# Define FLIPW (ray) (word) (ray) [0]) * 256) + (ray) [1])

8. convert a Word into two bytes in LSB format.

# Define FLOPW (ray, val )\

(Ray) [0] = (val)/256 );\

(Ray) [1] = (val) & 0xFF)

9. Get the address of a variable (word width)

# Define B _PTR (var) (byte *) (void *) & (var ))

# Define W_PTR (var) (word *) (void *) & (var ))

10 to obtain the high and low bytes of a word.

# Define WORD_LO (xxx) (byte) (word) (xxx) & 255 ))

# Define WORD_HI (xxx) (byte) (word) (xxx)> 8 ))

11. Return a multiple of 8 nearest to X.

# Define RND8 (x) + 7)/8) * 8)

12. convert a letter into uppercase letters.

# Define UPCASE (c)> = 'A' & (c) <= 'Z ')? (C)-0x20): (c ))

13. determines whether the character is a decimal number.

# Define DECCHK (c)> = '0' & (c) <= '9 ')

14. determines whether the character is a hexadecimal number.

# Define HEXCHK (c)> = '0' & (c) <= '9') | \

(C)> = 'A' & (c) <= 'F') | \

(C)> = 'A' & (c) <= 'F '))

15. A method to prevent overflow

# Define INC_SAT (val) (val = (val) + 1> (val ))? (Val) + 1: (val ))

16. returns the number of array elements.

# Define ARR_SIZE (a) (sizeof (a)/sizeof (a [0])

17. Return the value MOD_BY_POWER_OF_TWO (X, n) = X % (2 ^ n) at the end of n)

# Define MOD_BY_POWER_OF_TWO (val, mod_by )\

(Dword) (val) & (dword) (mod_by)-1 ))

18. For the structure of IO space ing in the bucket, Input/Output Processing

# Define Indium (port) (* (volatile byte *) (port )))

# Define inpw (port) (* (volatile word *) (port )))

# Define inpdw (port) (* (volatile dword *) (port )))

 

# Define outp (port, val) (* (volatile byte *) (port) = (byte) (val )))

# Define outpw (port, val) (* (volatile word *) (port) = (word) (val )))

# Define outpdw (port, val) (* (volatile dword *) (port) = (dword) (val )))

[Add]

19. Use some macro tracking for debugging

The a n s I Standard specifies five predefined macro names. They are:

_ L I N E _

_ F I L E _

_ D a t e _

_ T I M E _

_ S t d c _

If compilation is not standard, only a few of the above macro names are supported or not supported at all. Remember to compile the program

Other predefined macro names may also be provided.

The _ l I n e _ and _ f I l e _ macro commands have been discussed in the section about # l I n e. The remaining macro names are discussed here.

The _ d at e _ macro command contains a string in the form of month, day, or year, which indicates the date when the source file was translated to the code.

The time when the source code is translated to the target code is included in _ t I M E _ as a string. String format: minute: second.

If the implementation is standard, the macro _ s t d c _ contains the decimal constant 1. If it contains any other number, the implementation is

Non-standard.

You can define macros, for example:

When _ DEBUG is defined, the output data and the row of the file

# Ifdef _ DEBUG

# Define DEBUGMSG (msg, date) printf (msg); printf ("% d", date, _ LINE _, _ FILE _)

# Else

# Define DEBUGMSG (msg, date)

# Endif

20. macro definition to prevent usage from being incorrect

Enclosed in parentheses.

Example: # define ADD (a, B) (a + B)

Use the do {} while (0) statement to include multiple statements to prevent errors.

Example: # difne DO (a, B) a + B ;\

A ++;

Application Time: if (....)

DO (a, B); // generate an error

Else


Solution: # difne DO (a, B) do {a + B ;\

A ++;} while (0)

Usage of "#" and "#" in macro

I. general usage
We use # to convert the macro parameter into a string, and # to combine the two macro parameters.
Usage:
# I nclude
# I nclude
Using namespace std;

# Define STR (s) # s
# Define CONS (a, B) int (a ## e ## B)

Int main ()
{
Printf (STR (vck); // output string "vck"
Printf ("% d \ n", CONS (2000); // 2e3 output:
Return 0;
}

2. When the macro parameter is another macro
It should be noted that all macro parameters that use '#' or '#' in macro definition will not be expanded.

1. Non-'#' and '#'
# Define TOW (2)
# Define MUL (a, B) (a * B)

Printf ("% d * % d = % d \ n", TOW, TOW, MUL (TOW, TOW ));
The Macros in this line will be expanded:
Printf ("% d * % d = % d \ n", (2), (2), (2) * (2 )));
The TOW parameter in MUL is expanded to (2 ).

2. When '#' or '#' is available
# Define A (2)
# Define STR (s) # s
# Define CONS (a, B) int (a ## e ## B)

Printf ("int max: % s \ n", STR (INT_MAX); // INT_MAX # I nclude
This row is expanded:
Printf ("int max: % s \ n", "INT_MAX ");

Printf ("% s \ n", CONS (A, A); // compile error
This line is:
Printf ("% s \ n", int (AeA ));

INT_MAX and A will not be expanded. However, the solution to this problem is simple. add another layer of intermediate conversion macro.
The purpose of adding this macro layer is to expand all macro parameters in this layer, so that the macro (_ STR) in the conversion macro can get the correct macro parameters.

# Define A (2)
# Define _ STR (s) # s
# Define STR (s) _ STR (s) // convert macro
# Define _ CONS (a, B) int (a ## e ## B)
# Define CONS (a, B) _ CONS (a, B) // convert a macro

Printf ("int max: % s \ n", STR (INT_MAX); // The maximum value of INT_MAX, int type, is a variable # I nclude
Output: int max: 0x7fffffff
STR (INT_MAX) --> _ STR (0x7fffffff) and then convert it to a string;

Printf ("% d \ n", CONS (A, ));
Output: 200
CONS (A, A) --> _ CONS (2), (2) --> int (2) e (2 ))

Iii. Special Application Cases of '#' and '#'
1. Merge anonymous variable names
# Define ___ ANONYMOUS1 (type, var, line) type var # line
# Define _ ANONYMOUS0 (type, line) ___ ANONYMOUS1 (type, _ anonymous, line)
# Define ANONYMOUS (type) _ ANONYMOUS0 (type, _ LINE __)
For example, ANONYMOUS (static int); that is, static int _ anonymous70; 70 indicates the row number;
First layer: ANONYMOUS (static int); --> _ ANONYMOUS0 (static int, _ LINE __);
Layer 2: --> ___ ANONYMOUS1 (static int, _ anonymous, 70 );
Layer 3: --> static int _ anonymous70;
That is, the macro of the current layer can only be unlocked at each time, so _ LINE _ can be unlocked at the second layer;

2. fill Structure
# Define FILL (a) {a, #}

Enum IDD {OPEN, CLOSE };
Typedef struct MSG {
IDD id;
Const char * msg;
} MSG;

MSG _ msg [] = {FILL (OPEN), FILL (CLOSE )};
Equivalent:
MSG _ msg [] = {OPEN, "OPEN "},
{CLOSE, "CLOSE "}};

3. Record File Name
# Define _ GET_FILE_NAME (f) # f
# Define GET_FILE_NAME (f) _ GET_FILE_NAME (f)
Static char FILE_NAME [] = GET_FILE_NAME (_ FILE __);

4. Obtain the buffer size of the string corresponding to the value type.
# Define _ TYPE_BUF_SIZE (type) sizeof # type
# Define TYPE_BUF_SIZE (type) _ TYPE_BUF_SIZE (type)
Char buf [TYPE_BUF_SIZE (INT_MAX)];
--> Char buf [_ TYPE_BUF_SIZE (0x7fffffff)];
--> Char buf [sizeof "0x7fffffff"];
This is equivalent:
Char buf [11];

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.