##
Connector and
#
Character
##
Connector
The number consists of two well numbers. Its function is
Macro definition with Parameters
Medium
Bind two substrings
(Token)
Join
Up
To form
New substrings. But it cannot be the first or last substring. The so-called substring
(Token)
It means that the compiler can
The minimum syntax unit that can be identified. The specific definition has a detailed explanation in the compilation principle, but it does not matter if you do not know. It is worth noting that
# Connection
Character
Yes
When the passed parameter is
StringSubstitution
. Next let's take a look
How they work. This is
MSDN
.
Suppose the program has defined such a macro with parameters:
# Define paster (n)
Printf ("token" # n "= % d", token # n)
At the same time, an integer variable is defined:
Int token9 = 9;
Call this macro in the following way in the main program:
Paster (9 );
During compilation, the above sentence is extended:
Printf ("token" "9" "=
% D ", token9 );
Detailed explanation:
# N
Equivalent
"N", token # n
Equivalent
Token9,
Note
##
Cannot be
Two
#,
They have different meanings.
Note that in this example,
Paster (9 );
This
"9"
As a string
"Token"
Connected together to become
Token9
. While
# N
Also
"9"
.
As you can imagine, the program running above is printed on the screen.
Token9 = 9
Note that # And # cannot be used in disorder.
========================================================== ======================================
Both ##and ## are pre-processing operators in C, which are usually used in # define.
Operator # is usually called the stringize operator, which converts the string after it into a string surrounded by double quotation marks. For example:
# Define mkstr (s) # s
Printf (mkstr (I like C ));
Equivalent to: printf ("I like C ");
Operator # combine two tokens to generate a new token. Example:
# Define Concat (a, B) a # B
Printf ("% d", Concat (x, y ));
Equivalent to: printf ("% d", XY );
# Connector
[Baku ]:
# Definetasksetup (taskname, tasksetupparams )/
Tasksetup _ # taskname (taskname ### API, tasksetupparams)
When you call tasksetup (AAA, BBB ),
Tasksetup_aaa (aaa_api, BBB)
[Studyall123 ]:
Strong ls!
[Chenyu2202863 ]:
Learned
[Goodluckyxl ]:
# It is just a common connection function used in macros
It is generally used for regular naming or calling.
A1 A2 A3
Then we can connect f (I) A # I.
[Happylion2008 ]:
Macro operator in C language. LS has explained in detail. There are also # connector usage.
It should be explained in the pre-compiled chapter in C language textbooks.
Preprocessing commands and
Usage of macro definition (1)
Author: Liu Wei
Monday, June 24 2002 AM
People who are new to MFC programming are often intimidated by various macro definitions and preprocessing commands generated by the MFC wizard. However, preprocessing and macro definitions are
Is a powerful tool in C language. They can be used for simple source code control, version control, warning, or some special functions.
A classic example
The most classic example of using preprocessing and macro definition is to add a header file to avoid the header file being compiled twice. In this case, there is a file headerfile. h. It is included in headerfile1.h and also included in headerfile2.h. Now there is a CPP file, implement. cpp contains headerfile1.h and headerfile2.h:
# Include "headerfile1.h"
# Include "headerfile2.h"
Assume that headerfile. h defines
The global variable iglobal.
Int iglobal;
During compilation, the compiler compiles the headerfile twice and finds that iglobal is defined twice. In this case, a variable redefinition compilation error occurs.
The traditional solution is to use # ifdef and # endif to avoid repeated compilation of header files. In the preceding example, you only need to add the following lines:
# Ifndef smartnose_2002_6_21_headerfile_h
# Define smartnose_2002_6_21_headerfile_h
Int iglobal;
# Endif
After careful consideration of the macro definition above, we will find that when the compiler has compiled headerfile. h
Later, the macro smartnose_2002_6_21_headerfile_h will be defined, and INT will be skipped for future compilation of headerfile. h.
Iglobal. Of course, the macro smartnose_2002_6_21_headerfile_h can be defined at will,
Macros cannot be the same as macros defined in other files. Therefore, MFC always uses a random macro with a very long length in automatically generated files, but I don't think this is necessary, I suggest you add this macro
Some meaningful information, such as the author, file name, file creation time, and so on, because we sometimes forget to add this information to the comment.
In VC. net, we will no longer see these macro definitions,
This is because a preprocessing command is generally used here:
# Pragma once
You only need to add this command at the beginning of the header file to ensure that the header file is compiled once. This command is actually available in vc6, but it is not widely used in consideration of compatibility.
Source code version control
When we develop multiple versions for many platforms, pre-compilation commands and macro definitions can also help us. Assume that we are now running Windows and Linux
We developed a set of software. Because of the differences between the two systems, we had to control the source code version in the program. For example, we can use the standard C
Malloc function, but we want
Use the heapalloc API on Windows. The following code demonstrates this situation:
Main ()
{
....................
# Ifdef _ windows_platform
Heapalloc (5 );
# Else
Malloc (5 );
# Endif
....................
}
When we compile this program on windows, we only need to define the _ windows_platform macro, then the heapalloc statement can
Enough. In this way, we can implement different versions of code for different platforms in the same file, while maintaining a good program structure. In many cases, we can also use different computations for a method.
And then use the macro
Define to select one of them for compilation based on different situations. This is the most widely used in MFC applications. The most obvious is the frequent
# Ifdef _ debug
......................... Some code ...........
# Endif
Such code plays a role in debugging of the application.
# Pragma command
Among all the pre-processing commands, the # pragma command may be the most complex, and its function is to set the compiler's
Status or indicates the compiler to complete some specific actions. The format is generally
# Pragma Para
Here, Para is a parameter. Below are some common parameters.
Message parameter. The Message parameter is one of my favorite parameters. It can output the corresponding information in the compilation information output window.
The control of source code information is very important. The usage is as follows:
# Pragma message ("message text ")
When the compiler encounters this instruction, it prints the message text in the compilation output window.
When we define many Macros in the program to control the source code version, we may forget whether these macros are correctly set, in this case, we can use this command to check it during compilation. False
If we want to determine whether we have defined the _ X86 macro in the source code, we can use the following method:
# Ifdef _ X86
# Pragma message ("_ X86 macro activated !")
# Endif
After we define the _ X86 macro, the application will display "_ X86 macro activated!" in the compilation output window during compilation !". We won't be scratching our heads because we don't remember some specific macros we defined.
The other pragma parameter that is used more frequently is code_seg. Format:
# Pragma code_seg (["section-name" [, "section-class"])
It can set the code segment where function code is stored in the program. It is used when we develop the driver.
The last commonly used command is the # pragma once Command mentioned above.
Pre-defined macros of VC
In VC, a type of macros are not defined by the # define statement, but can be recognized by the compiler itself. These macros are also very useful. Let's take a look at the first one, which is also used in MFC
The most frequently used one: __file __.
When the compiler encounters this macro, it expands it into the file name of the currently compiled file. Now, we can immediately think about what we can do with it. When an application error occurs, we can report this error.
For example, in the test. cpp file
The following code is available:
Try
{
Char * P = new (char [10]);
}
Catch (cexception * E)
{
Trace ("There is an error in file: % s/n" ,__ file __);
}
When the program runs, if an error occurs in memory allocation, there is an error in file: test. CPP, of course, we can also display this error message elsewhere.
If we can record the row in which the error occurs, we are lucky that, like the _ file _ macro definition, there is also a macro that records the number of rows of the current Code,
This macro is _ line __. Using the two macros above, we can write an Assert statement similar to that provided by VC. The method is as follows:
# Define myassert (X )/
If (! (X ))/
MessageBox (_ FILE __,__ LINE __, NULL, MB_ OK );
In an application, we can use it like an ASSERT statement. When an error occurs, a dialog box is displayed. Its title and content tell us the file and code line number of the error, convenience
Debugging, which is very useful for projects that cannot use the ASSERT statement.
In addition to these two macros, the _ TIME __, _ DATE __, and _ TIMESTAMP _ macro that records the Compilation TIME.
With these predefined macros, we can generate almost the same complete source code information report as that generated by VC.
Conclusion
Open the source code of MFC and Linux, macro definition occupies almost half of the sky, message ing, queue operations, platform transplantation, version management, and even kernel module Disassembly
Macros used for installation
Definition completed. It is no exaggeration to say that some files can only see macro definitions. So learning macro definition,
Skillful Use of macros
Definition is critical for learning C language and even VC.
In the previous article, I demonstrated several commonly used macro definitions and preprocessing commands, but it can be said that these are quite common skills. The macro definition and
The usage of pre-processing commands is also very important in ATL, MFC, and LINUX.
# Connector and # Connector
# The Concatenation symbol is composed of two pound signs. Its function is to connect two substrings (tokens) in the macro definition with parameters to form a new substring. But it cannot be the first or
Is the last substring. The so-called token refers to the minimum syntax unit that the compiler can recognize. The specific definition has a detailed explanation in the compilation principle, but it does not matter if you do not know. Also worth noting
Yes # Replace the passed parameter with a string. Let's take a look at how they work. This is an example on msdn.
Suppose the program has defined such a macro with parameters:
# Define Paster (n) printf ("token" # N "= % d", Token # N)
At the same time, an integer variable is defined:
Int token9 = 9;
Call this macro in the following way in the main program:
Paster (9 );
During compilation, the above sentence is extended:
Printf ("token" "9" "= % d", token9 );
Note that in this example, Paster (9 );
The "9" is regarded as a string and connected with the "token", thus becoming
Token9. # N is also replaced by "9.
As you can imagine, the result of running the program above is to print token9 = 9 on the screen.
In ATL programming, we often see the following section when viewing its source code:
# Define implements_interface (ITF )/
{& IID _ # ITF, entry_is_offset, base_offset (_ itcls, ITF )},
We often use it like this without thinking:
......
Implements_interface (ICAT)
......
In fact, iid_icat is defined by the ATL wizard elsewhere. When there is no wizard, you only need to follow the rules that add IID _ before your interface name to define the guid
You can also use this macro. This kind of technique may be rarely used in the actual development process, but ATL is widely used, and many of them have such source code.
Important. One of my friends is busy because I don't know how the implements_interface macro is defined, and I accidentally changed the iid_icat definition.
Day.
Linux
Strange circles
I was puzzled by a small Macro when I first started reading Linux:
# Define wait_event (WQ, condition )/
Do {/
If (condition )/
Break ;/
_ Wait_event (WQ, condition );/
} While (0)
This is a strange loop. It only runs once at all. Why not remove the do {...} while statement
What about structure? I once called it a "Strange Circle" in my mind ". It turns out to be a very clever technique. It may often cause troubles in the project, and the above definition can ensure that these troubles do not occur. The following is an explanation:
Suppose there is such a macro definition.
# Define macro (condition )/
If (condition) dosomething ();
Use this macro in the program as follows:
If (temp)
Macro (I );
Else
Doanotherthing ();
Everything looks normal, but think about it. This macro was launched as follows:
If (temp)
If (condition) dosomething ();
Else
Doanotherthing ();
At this time, else is not the first if language
The statement matches the second if statement. The compilation is successful, but the running result must be incorrect.
To avoid this error, do {...} is used {....} While (0)
It is encapsulated into an independent syntax unit, so that it will not be confused with the context. At the same time, because most compilers can recognize do {...} While (0) This
Useless loop and optimization, so using this method will not lead to lower program performance.
A few small warnings
As Microsoft claims, macro definition and pre-compiler commands are powerful, but they make the program difficult to debug. Therefore, do not save your strings when defining macros, and strive for a complete description.
This macro function. At the same time, do {…} should be used if necessary when defining macros (for example, if statements are used {...} While (0) closes it. When defining macros, you must pay attention to the dependency between macros,
Try to avoid this dependency. The following is an example.
An integer queue composed of a static array is set. This method is used in the definition:
Int array [] = {5, 6, 7, 8 };
We also need to traverse this array in the program. The common practice is to use a macro definition.
# Define ELE_NUM 4
................................
...................................
For (int I = 0; I <ELE_NUM; I ++)
{
Cout <array [I];
}
For some accidental reason, we deleted an element in the definition and changed it:
Array [] = {5, 6, 7}
But forget to modify the ELE_NUM value. In the above Code, an access exception occurs immediately and the program crashes. Then we went to sleep for debugging and finally found the problem lies in the macro definition.
To solve this problem, do not use
Array [] = {....} This definition, while explicitly declaring the size of the array:
Array [ELE_NUM] = {....}
In this way, when changing the array definition, we will not remember to change the macro definition. In short, macro definition can be used when macro definition is used.
All places are used.
Another interesting phenomenon I found is:
Suppose there is a course management system, and the number of students is defined
# Define stu_num 50
The number of teachers is also 50, so many people use stu_num for all the places involving the number of teachers.
This macro. One of the students was fired in the past semester and the system needs to change. What should we do? Simple use # define stu_num 49? If so, a teacher will be fired and we have to find
Stu_num macro and then judge whether it represents the number of students. If so, change it to 49. God, this macro definition
It makes more trouble than using it. The correct method should be to define another macro for the number of instructors:
# Define tea_num 50
When the number of students changes, the system changes as long as stu_num is defined as 49. Institute
Therefore, when there is no inevitable relationship between the two quantities in the program, do not use one macro to replace the other, it will make your program unable to be modified.
Finally, we recommend that beginners of C/C ++ use as many macros and
Pre-compiled commands. Let's take a look at the source code of MFC, ATL, or Linux. You will find the reason for the powerful C language.