Summary of common macro definitions in 20 C languages

Source: Internet
Author: User
Tags mul

01: Prevent a header file from being repeatedly included

#ifndef Comdef_h
#define Comdef_h
Header file Contents
#endif

02: Redefine Some types
Prevents different types of bytes generated due to various platforms and compilers, which facilitates portability.

typedef unsigned char Boolean; /* Boolean value type. */
typedef unsigned long int uint32; /* Unsigned-bit value */
typedef unsigned short uint16; /* Unsigned-bit value */
typedef unsigned char uint8; /* Unsigned 8 bit value */
typedef signed Long int int32; /* Signed-bit value */
typedef signed short Int16; /* Signed-bit value */
typedef signed CHAR int8; /* Signed 8 bit value */

The following is not recommended for use
typedef unsigned char byte; /* Unsigned 8 bit value type. */
typedef unsigned short word; /* unsinged-bit value type. */
typedef unsigned long DWORD; /* Unsigned-bit value type. */
typedef unsigned char uint1; /* Unsigned 8 bit value type. */
typedef unsigned short Uint2; /* Unsigned-bit value type. */
typedef unsigned long uint4; /* Unsigned-bit value type. */
typedef signed Char Int1; /* Signed 8 bit value type. */
typedef signed short Int2; /* Signed-bit value type. */
typedef long int int4; /* Signed-bit value type. */
typedef signed Long SINT31; /* Signed-bit value */
typedef signed short sint15; /* Signed-bit value */
typedef signed Char SINT7; /* Signed 8 bit value */

03: Get a Byte or a word on the specified address

#define MEM_B (x) (* (BYTE *) (x))
#define MEM_W (x) (* ((Word *) (x)))

04: Find maximum and minimum values

#define MAX (x, y) ((> (y))? (x): (y))
#define MIN (x, Y) ((() < (y))? (x): (y))

05: Gets the offset of a field in the struct (struct)

#define FPOS (Type,field) ((DWORD) & ((type *) 0)->field)

06: Get the number of bytes occupied by field in a struct

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

07: Convert two bytes to a word in LSB format

#define FLIPW (Ray) (((Word) (Ray) [0]) + (Ray) [1])

08: Convert a Word to two bytes in LSB format
#define FLOPW (Ray,val) (Ray) [0] = ((val)/256); (Ray) [1] = ((val) & 0xFF)

09: Get the address of a variable (word width)

#define B_PTR (Var) ((BYTE *) (void *) & (Var))
#define W_PTR (Var) ((Word *) (void *) & (Var))

10: Get 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: Returns a multiple of the nearest 8 that is larger than X

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

12: Convert one letter to uppercase

#define UPCASE (c) (((c) >= ' A ' && (c) <= ' Z ')? ((c) –0x20): (c))

13: Determine if a character is a number that is 10 in value

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

14: Determine if a character is a number that is 16 in value

#define HEXCHK (c) (((c) >= ' 0 ' && (c) <= ' 9 ') ((c) >= ' A ' && (c) <= ' F ') \
((c) >= ' A ' && (c) <= ' F '))

15: One way 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: Returns the value of an unsigned N-tailed Mod_by_power_of_two (X,n) =x% (2^n)

#define Mod_by_power_of_two (Val, mod_by) ((DWORD) (VAL) & (DWORD) ((mod_by)-1))

18: Input and output processing for IO space mapping in storage space structure

#define INP (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)))

19: Debug with some macro tracking

The ANSI standard describes five predefined macro names. They are:
__line__
__file__
__date__
__time__
__stdc__
__cplusplus is also defined in C + +.

If the compiler is not standard, it is possible to support only a few of the macro names above, or not at all. Remember that the compiler may also provide other predefined macro names.

__LINE__ and __FILE__ macros indicate that, #line指令可以改变它的值, simply speaking, when compiled, they contain the current number of lines and file names of the program.

The __DATE__ macro directive contains a string of months/days/years, indicating the date when the source file was translated to the code.
The __TIME__ macro directive contains the time that the program was compiled. Time is represented by a string, in the form: minutes: seconds
The meaning of the __STDC__ macro directive is defined at compile time. In general, if __STDC__ is already defined, the compiler will only accept standard C + + code that does not contain any non-standard extensions. If the implementation is standard, the macro __stdc__ contains a decimal constant of 1. If it contains any other number, the implementation is non-standard.
__cplusplus A compiler that is consistent with standard C + + defines it as a value that contains at least 6. Compilers that are inconsistent with standard C + + will use a numeric value that has 5 bits or less.

You can define macros, for example:
When the _DEBUG is defined, the output data information and the file where the
#ifdef _DEBUG
#define DEBUGMSG (msg,date) printf (msg);p rintf ("%d%d%d", Date,_line_,_file_)
#else
#define DEBUGMSG (Msg,date)
#endif

20: Macro definition prevents errors with parentheses contained.

For example:
Problematic definition: #define Dump_write (ADDR,NR) {memcpy (BUFP,ADDR,NR); BUFP + = nr;}
Definitions that should be used: #difne do (A, b) do{a+b;a++;} while (0)
For example:
if (addr)
Dump_write (ADDR,NR);
Else
Do_somethong_else ();
After the macro expands, it becomes this:
if (addr)
{memcpy (BUFP,ADDR,NR); BUFP + = nr;};
Else
Do_something_else ();

GCC considers that the IF statement has ended when it encounters the ";" in front of else, so that the later else is not in the IF statement. With the definition of do{} while (0), there is no problem in any case. Instead #difne do (A, b) do{a+b;a++;} while (0) is defined without error in any case.

Transferred from: http://www.linuxpig.com/2011/03/20-useful-c-defines/

Usage of "#" and "# #" in macros
I. GENERAL usage
We use # To change the macro argument to a string with # #把两个宏参数贴合在一起.
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 (2,3)); 2E3 Output: 2000
return 0;
}

Second, when the macro parameter is another macro
It is important to note that the macro parameter, where the macro definition is useful ' # ' or ' # # ', is no longer expanded.

1, non-' # ' and ' # # ' situations
#define TOW (2)
#define MUL (A, B) (a*b)

printf ("%d*%d=%d\n", TOW, TOW, MUL (Tow,tow));
This line of macros will be expanded to:
printf ("%d*%d=%d\n", (2), (2), ((2) * (2)));
The parameter tow in the MUL will be expanded to (2).

2, when there is ' # ' or ' # # '
#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
The Guild is expanded to:
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 are no longer being unfolded, but the solution to this problem is simple. Add an extra layer of intermediate conversion macros.
The intention of adding this layer is to expand all the macro parameters in this layer, then the macro (_STR) in the 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 macro

printf ("int max:%s\n", STR (Int_max)); The maximum value of the Int_max,int type, which is a variable #i nclude
Output is: int max:0x7fffffff
STR (Int_max)--_STR (0x7fffffff) and then convert to string;

printf ("%d\n", CONS (A, a));
Output is: 200
CONS (A, a)-_cons ((2), (2))-Int ((2) E (2))

Third, ' # ' and ' # # ' Some of the application exceptions
1. Merging 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__)
Example: ANONYMOUS (static int);  That is: static int _anonymous70; 70 indicates the line number of the row;
First layer: ANONYMOUS (static int); --__ANONYMOUS0 (static int, __line__);
Second layer:--___ANONYMOUS1 (static int, _anonymous, 70);
Third layer:--static int _anonymous70;
That is, you can only unlock the current layer of macros, so __line__ in the second layer can be untied;

2. Filling structure
#define FILL (a) {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. Get a string buffer size corresponding to a numeric 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 to:
Char buf[11];

Summary of common macro definitions in 20 C languages

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.