GCC precompilation # If, #elif, #endif以及常用宏定义

Source: Internet
Author: User
Tags arithmetic arithmetic operators lowercase mul naming convention
Reprint: http://blog.chinaunix.net/uid-26854432-id-3181585.html #if语句


#if语句会计算它后面的表达式, and checks the result of the expression, if the result is true (true), the subsequent statement is compiled, and if False (false), the subsequent statement is not compiled.

For example:

#if COUNT
Char *desc = "The Count is Non-zero";
#endif


Compile only if Count is not 0

Char *desc = "The Count is Non-zero";

Statement.

Here are some of the syntax rules for an expression that follows # if:

1) expressions can include shaping constants and macros, which must be assigned (the difference is defined)

2) You can use parentheses to specify the order of the expressions.

3) expressions can contain +,-,*,/,<< and >> arithmetic operators in the C language. These arithmetic operations use the value of the maximum representation of the integer type of the current platform, typically a 64-bit integer value.

4) Expressions can also include <,>,<=,>= and = = comparison operators.

5) expressions can include && and | | The logical operator.

6) The non-(!) operator reverses the result of an expression, such as: #if! (Limxp > 12)

If LIMXP > 12, then the result of the expression is false

7) #if也可以和defined语句一起使用 so that you can check whether a macro has been defined (or you can use #ifdef directly). Such as:

#if defined (MINXP)

This means that if MINXP is defined, then the expression is true. You can also precede the result with a non-(!) operator, such as:

#if!defined (MINXP)

This means that if MINXP is not defined, then the expression is true.

8) If an identifier is not defined, its value is always the 0,-WUNDEF option that can be used to generate this warning message.

9) Macros with parameters (GCC: Preprocessing statements--#define, #error和 #warning) are also 0 values in the expression, and the-WUNDEF option can be used to generate this warning message.

) #else提供另外的选择, such as:

#if mintxt <= 5
#define Mintlog 11
#else
#define Mintlog 14
#endif
One) #elif可以提供一个或多个的选择表达式, such as:

#if mintxt <= 5
#define Mintlog 11
#elif Mintxt = = 6
#define Mintlog 12
#elif Mintxt = = 7
#define Mintlog 13
#else
#define Mintlog 14
#endif



#ifdef

If the macro that follows the same line as the #ifdef is defined, then the statement block after the #ifdef is compiled, and the block ends with #endif. For example:

#ifdef Mintarray
int xarray[20];
#endif/* Mintarray */



#endif后面的注释语句并不是必须的/* Mintarray * *, but it's a good way to do it, so you know which macro you defined is the end position.

and #ifdef the idea of the opposite is #ifndef.
#if语句

#if语句会计算它后面的表达式, and checks the result of the expression, if the result is true (true), the subsequent statement is compiled, and if False (false), the subsequent statement is not compiled.

For example:

#if COUNT
Char *desc = "The Count is Non-zero";
#endif


Compile only if Count is not 0

Char *desc = "The Count is Non-zero";

Statement.

Here are some of the syntax rules for an expression that follows # if:

1) expressions can include shaping constants and macros, which must be assigned (the difference is defined)

2) You can use parentheses to specify the order of the expressions.

3) expressions can contain +,-,*,/,<< and >> arithmetic operators in the C language. These arithmetic operations use the value of the maximum representation of the integer type of the current platform, typically a 64-bit integer value.

4) Expressions can also include <,>,<=,>= and = = comparison operators.

5) expressions can include && and | | The logical operator.

6) The non-(!) operator reverses the result of an expression, such as: #if! (Limxp > 12)

If LIMXP > 12, then the result of the expression is false

7) #if也可以和defined语句一起使用 so that you can check whether a macro has been defined (or you can use #ifdef directly). Such as:

#if defined (MINXP)

This means that if MINXP is defined, then the expression is true. You can also precede the result with a non-(!) operator, such as:

#if!defined (MINXP)

This means that if MINXP is not defined, then the expression is true. #if语句


#if语句会计算它后面的表达式, and checks the result of the expression, if the result is true (true), the subsequent statement is compiled, and if False (false), the subsequent statement is not compiled.

For example:

#if COUNT
Char *desc = "The Count is Non-zero";
#endif


Compile only if Count is not 0

Char *desc = "The Count is Non-zero";

Statement.

Here are some of the syntax rules for an expression that follows # if:

1) expressions can include shaping constants and macros, which must be assigned (the difference is defined)

2) You can use parentheses to specify the order of the expressions.

3) expressions can contain +,-,*,/,<< and >> arithmetic operators in the C language. These arithmetic operations use the value of the maximum representation of the integer type of the current platform, typically a 64-bit integer value.

4) Expressions can also include <,>,<=,>= and = = comparison operators.

5) expressions can include && and | | The logical operator.

6) The non-(!) operator reverses the result of an expression, such as: #if! (Limxp > 12)

If LIMXP > 12, then the result of the expression is false

7) #if也可以和defined语句一起使用 so that you can check whether a macro has been defined (or you can use #ifdef directly). Such as:

#if defined (MINXP)

This means that if MINXP is defined, then the expression is true. You can also precede the result with a non-(!) operator, such as:

#if!defined (MINXP)

This means that if MINXP is not defined, then the expression is true.

8) If an identifier is not defined, its value is always the 0,-WUNDEF option that can be used to generate this warning message.

9) Macros with parameters (GCC: Preprocessing statements--#define, #error和 #warning) are also 0 values in the expression, and the-WUNDEF option can be used to generate this warning message.

) #else提供另外的选择, such as:

#if mintxt <= 5
#define Mintlog 11
#else
#define Mintlog 14
#endif
One) #elif可以提供一个或多个的选择表达式, such as:

#if mintxt <= 5
#define Mintlog 11
#elif Mintxt = = 6
#define Mintlog 12
#elif Mintxt = = 7
#define Mintlog 13
#else
#define Mintlog 14
#endif



#ifdef

If the macro that follows the same line as the #ifdef is defined, then the statement block after the #ifdef is compiled, and the block ends with #endif. For example:

#ifdef Mintarray
int xarray[20];
#endif/* Mintarray */



#endif后面的注释语句并不是必须的/* Mintarray * *, but it's a good way to do it, so you know which macro you defined is the end position.

and #ifdef the idea of the opposite is #ifndef.

8) If an identifier is not defined, its value is always the 0,-WUNDEF option that can be used to generate this warning message.

9) Macros with parameters (GCC: Preprocessing statements--#define, #error和 #warning) are also 0 values in the expression, and the-WUNDEF option can be used to generate this warning message.

) #else提供另外的选择, such as:

#if mintxt <= 5
#define Mintlog 11
#else
#define Mintlog 14
#endif
One) #elif可以提供一个或多个的选择表达式, such as:

#if mintxt <= 5
#define Mintlog 11
#elif Mintxt = = 6
#define Mintlog 12
#elif Mintxt = = 7
#define Mintlog 13
#else
#define Mintlog 14
#endif

#ifdef

If the macro that follows the same line as the #ifdef is defined, then the statement block after the #ifdef is compiled, and the block ends with #endif. For example:

#ifdef Mintarray
int xarray[20];
#endif/* Mintarray */

#endif后面的注释语句并不是必须的/* Mintarray * *, but it's a good way to do it, so you know which macro you defined is the end position.

and #ifdef the idea of the opposite is #ifndef.

In fact, these three are macros, the following detailed description: You have encountered these several macros for conditional compilation. In general, all lines in the source program are compiled. However, sometimes it is desirable to compile a part of the content only if certain conditions are met, that is, to specify the conditions for the compilation of some content, which is "conditional compilation". Sometimes, you want to compile a set of statements when a condition is met, and then compile another set of statements when the condition is not met.
The most common form of conditional compilation commands is:
#ifdef identifiers
Procedure Section 1
#else
Procedure Section 2
#endif

It does this: when the identifier is already defined (typically defined with the # define command), the program Segment 1 is compiled, or the program fragment 2 is compiled.
The #else part can also be not, namely:
#ifdef
Procedure Section 1
#denif

The "program segment" Here can be a statement group, or it can be a command line. This kind of conditional compilation can improve the generality of C source program. If a C source program is running on a system with different computer systems, there are some differences between the different computers. For example, we have a data type that should be represented in the Windows platform using the long type, whereas float is used on other platforms, which often requires the necessary modifications to the source program, which reduces the generality of the program. Can be compiled with the following conditions:
#ifdef WINDOWS
#define MYTYPE Long
#else
#define MYTYPE Float
#endif

If you are compiling a program on Windows, you can add it at the beginning of the program
#define WINDOWS

This compiles the following command line:
#define MYTYPE Long

If the following command line appears before this set of conditional compilation commands:
#define WINDOWS 0

The MyType in the pre-compiled program are replaced with float. In this way, the source program can be used for different types of computer systems without having to make any modifications. Of course, the above introduction is only a simple situation, can be based on this idea to design other conditional compilation.
For example, when you are debugging a program, you often want to output some of the required information, and no longer output it when debugging is complete. You can insert the following conditional compilation segments in the source program:
#ifdef DEBUG
Print ("Device_open (%p) \ n", file);
#endif

If you have the following command line in front of it:
#define DEBUG

The value of the file pointer is output when the program runs to debug the analysis. Simply remove the Define command line after debugging. Some people may feel that without conditional compilation can also achieve this purpose, that is, in debugging, add a batch of printf statements, after debugging one after the printf statement deleted. Indeed, this is possible. However, when you add more than one printf statement when debugging, the amount of work that is modified is significant. With conditional compilation, you do not have to one by one to revise the printf statement, just delete the previous "#define DEBUG" command, then all the conditional compilation with DEBUG identifier to make the printf statement does not work, that is, the role of unified control, like a "switch".
It is sometimes used in the following form:
#ifndef identifiers
Procedure Section 1
#else
Procedure Section 2
#endif

Just the first line is different from the first: Change "ifdef" to "ifndef". Its function is: If the identifier is not defined, compile the program segment 1, or compile the program segment 2. This form is contrary to the effect of the first form.
The above two forms of use are similar, depending on the need to choose one, depending on the convenience.
There is also a form of an expression that is followed by # If, not a simple identifier:
#if an expression
Procedure Section 1
#else
Procedure Section 2
#endif

It does this by compiling program segment 1 when the specified expression value is true (not 0), or by compiling program segment 2. A certain condition can be given beforehand to enable the program to perform different functions under different conditions.
For example: Enter a line of alphabetic characters, set conditional compilation as needed, to make the letters all uppercase, or all lowercase.
#define LETTER 1
Main ()
{
Charstr[20]= "C Language", C;
inti=0;
while((C=str[i])! = ' + ') {
i++;
#if Letter
if(c>= ' A ' &&c<= ' z ') c=c-32;
#else
if(c>= ' A ' &&c<= ' Z ') c=c+32;
#endif
printf ("%c", c);
}
}

The result of the operation is: C LANGUAGE
Now define letter 1, so that when the preprocessing condition compiles the command, because letter is true (not 0), the first if statement is compiled, and the run-time causes lowercase letters to be capitalized. If you change the first line of the program to:
#define LETTER 0

When preprocessing, the second if statement is compiled to make uppercase letters lowercase (uppercase letters with the corresponding lowercase ASCII code difference of 32). At this point the operation is:
C language
Some people will ask: without conditional compilation command and directly with the IF statement can also meet the requirements, with conditional compilation command What is the benefit of it. It is true that this problem can be handled completely without conditional compilation, but the target program is long (because all statements are compiled), and conditional compilation reduces the length of the target by reducing the compiled statement.   When the conditional compilation segment is relatively long, the length of the target program can be greatly reduced. #ifndef in the header file


Do not overlook the #ifndef in the first piece, this is a very important thing. For example, you have two C files, these two
All c files include the same header file. At compile time, these two C files are compiled together into a single executable file
, so the problem comes with a lot of conflicting statements.

or the contents of the head file in #ifndef and #endif. Regardless of whether your header file will be referenced by multiple files
Your header file will not be referenced by multiple files
, you have to add this. The general format is this:

#ifndef < identity >
#define < identity >

......
......

#endif

< identity > can theoretically be freely named, but the "identity" of each header file should be unique.
The naming convention for an identity is usually the header file name all uppercase, underlined, and the "." in the file name. It becomes the next row.
Lines, such as: stdio.h

#ifndef _stdio_h_
#define _stdio_h_

......

#endif C language Common macro definition tips

In C language programming, macro definition is a very important programming skill. With the use of macro definition, it can enhance the readability of the program, portability, convenience, flexibility and so on.

1. Prevent a header file from being repeatedly included:

#ifndef Comdef_h

#define Comdef_h

Header file Contents

#endif

When you build a project with multiple source files, it is possible to include the same header file in multiple files, if borrowing the macro definition above can prevent the same head file from being repeatedly included in the compilation. Because a # define COMDEF_H is always not defined when it compiles the first header file, it compiles all the contents of the header file, including defining the # define COMDEF_H. If you encounter the same header file that you want to compile as you compile and then go down, it will not compile the header file again because of the presence of the statement #ifndef Comdef_h.

2. Macros are defined so that the number of bytes of the same data type is not changed by different platforms or different compilers:

typedef unsigned char Boolean; /* Boolean Value type */

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

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

typedef unsigned char uint8; /* Unsigned 8bit Value * *

typedef signed Long int int32; /* Signed 32bit value * *

typedef signed short Int16; /* Signed 16bit value * *

typedef signed CHAR int8; /* Signed 8bit value * *

3. Get a byte or word for the specified address:

#define MEM_B (x) (* (Uint8 *) (x))

#define MEM_W (x) (* (UInt16 *) (x))

Note: Similar to this macro definition with multiple strings, be sure to add "()" because we know that the macro definition is just a simple character substitution feature.

4. Find the maximum and minimum values:

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

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

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

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

6. Convert two bytes to one word in LSB format:

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

or can be

#define FLIPW (DATA1,DATA2) (((Word) (data1) *256) + (DATA2))

7. Convert a word to two bytes in LSB format:

#define FLOPW (Ray,val) do{(Ray) [0]= ((val)/256); (Ray) [1] = ((val) &0xff);} while (0)

or can be

#define FLOPW (Data1,data2,val) do{data1= ((val)/256); data2 = ((val) &0xff);} while (0)

Note: The Do{}while (0) Here is to prevent the macro definition of multiple statements from being used in error. Like what:

if (...)

FLOPW (Ray,val)

Else

In the program code above if there is no Do{}while (0) in the macro definition FLOPW (ray,val), then we should change the statement to:

if (...)

{

FLOPW (Ray,val)

}

Else

{

}

8. Get the address of a variable:

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

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

Note: The macro definition statement in void * Declares that the address can be the address of any type of variable, BYTE * is declared as the address of a single-byte variable, and Word * declares the address of a double-byte variable.

9. Get a high and low byte:

#define WORD_LO (XXX) ((byte) ((WORD) (XXX) &0xff))

#define WORD_HI (XXX) ((byte) ((WORD) (XXX) >>8))

10. Returns a multiple of the nearest 8 that is larger than x:

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

11. Convert one letter to uppercase:

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

It also corresponds to converting one letter to lowercase:

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

Note: If you don't remember the ASCII difference between uppercase and lowercase, you can change the 0x20 to (' A '-' a '), but here the lowercase ASCII value is greater than the uppercase ASCII value you should remember.

12. One way to prevent overflow:

#define INC_SAT (val) (val = (val) +1 > (val))? (val) +1: (val))

It can also be made into a loop count (adding a counter Val is an unsigned integer):

#define INC_SAT (val) (val = (val) +1 > (val))? (val) +1: (0))

13. Use of "#" and "# #" in Macros:

General usage:

Use "#" to change the macro parameter to a string, using "# #" to combine two macro parameters

Routines:

#include

#include

#define STR (s) #s

#define CONS (A, b) int (a# #e # #b)

int main ()

{

printf (STR (VCK)); Output string "Vck"

printf ("%d", CONS (2,3)); 2E3 Output: 2000

return 0;

}

When the macro parameter is another macro, note that the macro definition is useful for "#" or "# #" where the macro parameters are no longer expanded:

non-"#" and "# #" cases:

Routines:

#define TOW (2)

#define MUL (A, B) (a*b)

printf ("%d*%d=%d", Tow,tow,mul (Tow,tow));

The line can be expanded to printf ("%d*%d=%d", (2), (2), ((2) * (2)));

there are "#" or "# #" cases:

Routines:

#define A (2)

#define STR (s) #s

#define CONS (A, b) int (a# #e # #b)

printf ("Int max:%s", STR (Int_max)); Int_max in include

The line expands to printf ("Int max:%s", "Int_max");

That is, just expand the macro str (s), and the next level of macro Int_max is not expanded

printf ("%s", CONS (A,a));

This line of compilation will produce an error because it expands to printf ("%s", int (AeA));

In order to solve the problem that cannot be expanded, we can add a layer of intermediate conversion macro to achieve all the macro expansion, if you are not sure whether you use the macro nesting problem, it is best to add a level intermediate conversion macro, so as not to produce an error.

Routines:

#define A (2)

#define _STR (s) #s

#define STR (s) _str (s)

#define _cons (A, b) int (a# #e # #b)

#define CONS (A, B) _cons (A, B)

printf ("Int max:%s", STR (Int_max));

The Int_max will be expanded, it is the maximum value of the int type, and the output is: int max:0x7fffffff

printf ("%d", CONS (A,a));

Two layers of macros will be able to expand, CONS (A,a) à_cons ((2), (2)) Àint ((2) E (2)), output: 200

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.