Some predefined Macros in the c Standard
When writing code yesterday, you must obtain the current Compilation Time in the code to dynamically use the version information. Therefore, some predefined Macros in the C standard are used. Here we will summarize the following macros defined in the C standard:
_ Date _ Date of preprocessing (string text in the form of "Mmm dd YYYY", such as May 27 2006)
_ File _ represents the string Text of the current source code file name, including the detailed path, such as G:/Program/study/C ++/test1.c
_ Line _ represents the integer constant of the row number in the current source code.
_ Time _ source file Compilation Time in the format of "HH: mm: SS", for example, 09: 11: 10;
_ FUNC _ The Name Of The current function, which is supported in a later version of the compiler.
_ Function _ name of the current function
For macros such as _ file __,__ line __,__ func __,__ function _, it is very useful in program debugging, because you can easily know the row of the file to which the program runs and the function.
For _ date __,__ time _, you can obtain the compilation time. For example, the following code uses a macro to obtain the Compilation Time and sscanf () to obtain the specific year, month, day, hour, minute, and second data, it can be used in the code. In my code, the data is used as the version ID, and the new version and whether the upgrade is required are determined based on the data.
Char * creationdate = _ date _ "," _ time __;
Sscanf (creationdate, "% S % d, % d: % d", month, & day, & year, & hour, & min, & Sec );
Preprocessing command # pragma and predefined macros -- reprint
I,C. predefined macros
The c Standard specifies some predefined macros, which are often used in programming.
_ Date _ Date of preprocessing
_ File _ represents the string of the current source code file name
_ Line _ represents the integer constant of the row number in the current source code file.
When _ stdc _ is set to 1, the implementation follows the C standard.
_ Stdc_hosted _ is set to the local environment; otherwise, it is set to 0.
When _ stdc_version _ Is c99, it is set to 199901l.
_ Time _ source file Compilation Time
Provided by _ FUNC _ c99 is the string of the function name.
It is useful for macros such as _ file __,__ line __,__ func _ in program debugging, because you can easily know the row of the file to which the program runs and the function.
For example:
# Include
# Include
Void why_me ();
Int main ()
{
Printf ("the file is % s/n", _ file __);
Printf ("the date is % s/n", _ date __);
Printf ("the time is % s/n", _ time __);
Printf ("the version is % s/n" ,__ stdc1_version __);
Printf ("this is line % d/N", _ line __);
Printf ("this function is % s/n", _ FUNC __);
Why_me ();
Return 0;
}
Void why_me ()
{
Printf ("this function is % s/n", _ FUNC __);
Printf ("this is line % d/N", _ line __);
}
Ii. # Line and # error
# Line is used to reset the row number and file name specified by _ line _ and _ file _ macros.
Usage: # line number filename
Example: # Line 1000 // set the current row number to 1000
# Line 1000 "Lukas. c" // set the row number to 1000 and the file name to Lukas. C.
# The error command causes the pre-processor to send an error message containing the text in the command. The purpose of this command is to provide certain information before the program crashes.
Iii. # pragma
Among all the pre-processing commands, the # pragma command may be the most complex.# The role of Pragma is to set the compiler status or instruct the compiler to complete some specific actions.# The Pragma command provides a method for each compiler to provide the unique features of the host or operating system while maintaining full compatibility with C and C ++ languages. According to the definition, the compilation instructions are proprietary to machines or operating systems and are different for each compiler.
The format is generally: # pragma para
Here, para is a parameter. Below are some common parameters.
(1) Message parameter. The message parameter is one of my favorite parameters.Output the relevant information in the compilation information output window.This is very important for controlling source code information. 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. Suppose we want to determine whether we have defined the _ x86 macro in the source code. The following method can be used:
# Ifdef _ x86
# Pragma message ("_ x86 macro activated !")
# Endif
After we define the _ x86 macro, the application will display "_
X86 macro activated !". We won't be scratching our heads because we don't remember some specific macros we defined.
(2) 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.
(3)# Pragma once(Common)
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 considering its compatibility.
(4) # pragma hdrstop indicates that the pre-compiled header file ends here, and the subsequent header files are not pre-compiled. BCB can pre-compile the header file to speed up the link, but if all header files are pre-compiled, it may occupy too much disk space. Therefore, this option is used to exclude some header files.
Sometimes there is a dependency between units. For example, unit a depends on unit B. Therefore, Unit B must be compiled before unit. You can use # pragma startup to specify the compilation priority. If # pragma package (smart_init) is used, BCB will be compiled based on the priority.
(5) # pragma resource "*. DFM" indicates adding resources in the *. DFM file to the project. *. DFM defines the appearance of a form.
(6) # pragma warning (Disable: 4507 34; once: 4385; error: 164) is equivalent:
# Pragma warning (Disable: 4507 34)/* do not display the 4507 and 34 Warnings. If warning 4507 and warning 34 always appear during compilation,
I think there will be no errors. You can use this command. */
# Pragma warning (once: 4385) // only one warning message is reported once
# Pragma warning (error: 164) // the error message 164 is used as an error.
This pragma warning also supports the following formats:
# Pragma warning (push [, N])
# Pragma warning (POP)
Here N represents a warning level (1---4 ).
# Pragma warning (push) saves the existing warning status of all warning information.
# Pragma warning (push, n) saves the existing warning status of all warning information and sets the global warning level to n.
# Pragma warning (POP) pops up the last warning message to the stack, and all changes made between the inbound and outbound stacks are canceled. For example:
# Pragma warning (push)
# Pragma warning (Disable: 4705)
# Pragma warning (Disable: 4706)
# Pragma warning (Disable: 4707)
//.......
# Pragma warning (POP)
At the end of the Code, save all warning information (including 4707, and ).
(7) Pragma comment (...)
This command puts a comment record into an object file or executable file.
Common lib keywords can help us to connect to a library file.
(8) progma pack (N)
Specify the structure alignment! # Pragma pack (n) to set the variable to n-byte alignment. N-byte alignment means the offset of the Start address of the variable. First, if n is greater than or equal to the number of bytes occupied by the variable, the offset must meet the default alignment mode, second, if n is less than the number of bytes occupied by the variable type, the offset is a multiple of N, and the default alignment is not required. The total size of the structure also has a constraint, which is divided into the following two cases: if n is greater than the number of bytes occupied by all member variable types, the total size of the structure must be a multiple of the space occupied by the largest variable; otherwise, it must be a multiple of N. The following is an example of its usage.
# Pragma pack (push) // save alignment status
# Pragma pack (4) // set to 4-byte alignment
Struct Test
{
Char M1;
Double M4;
Int m3;
};
# Pragma pack (POP) // restore alignment
To test this function, you can use sizeof () to test the length of the struct!
When you write a DLL, the compiler has different name resolution rules for C and C ++, so you can use
# Ifndef _ stdc __
Extern "C" Void function ();
# Else
Void function ();
# Endif
_ Line _ Insert the current source code line number into the source code
_ File _ Insert the current source code file name in the source code
_ Date _ Insert the current compilation date in the source code (note the difference from the current system date 〕
_ Time _ Insert the current Compilation Time in the source code (note the difference from the current system time 〕
_ Stdc _ when the program strictly follows the ansic standard, the identifier is assigned 1.
----------------------------------------------------------------------------
Identifiers _ line _ and _ file _ are usually used to debug programs; identifiers _ date _ and _ time _ are usually used to add a time sign to the compiled program to distinguish different versions of the program. When the program strictly follows the ansic standard, the identifier _ stdc _ will be assigned a value of 1. When the program is compiled in C ++, the identifier _ cplusplus will be defined.
# Include
Int main ()
{
Printf ("Location of the output row in the source program: % d/N", _ line __);
Printf ("the program file name is: % s/n", _ file __);
Printf ("current date: % s/n", _ date __);
Printf ("Current Time: % s/n", _ time __);
Return 0;
}
# Include
Void main (void)
{
Printf ("% d" ,__ line _); // line 5
}
Result: 5
// Standard predefined macro. cpp: defines the entry point for the console application.
//
# Include "stdafx. H"
# Include
Void main (void)
{
Printf ("% d" ,__ line _); // line 5
}
Compiler macro usage Summary
In C/C ++, the macro summarizes various compilation commands in the source code of the C program. These commands are called preprocessing commands. Although they are not actually part of the C language, they extend the C programming environment. This section describes how to use preprocessing programs and annotations to simplify the program development process and improve the readability of the program. The C language Preprocessing Program defined by ANSI includes the following commands:
# Define, # error, # include, # If, # else, # Elif, # endif, # ifdef, # ifndef, # UNDEF, # Line, # pragma, etc. Obviously, all the pre-processing commands start with a symbol #, which is described below.
Command # defineDefines an identifier and a string. Each time This identifier is encountered in the source program, it is replaced by a defined string. The ANSI standard defines the identifier as a macro name, and the replacement process is called macro replacement. The command is generally in the following format:
# Define identifier string
Note:
? This statement does not have a semicolon. There can be any space between the identifier and the string. Once the string starts, it ends only with a new row.
? After the macro name is defined, it can become part of other macro name definitions.
? Macro replacement only replaces macro identifiers with text strings, provided that the macro identifiers must be identified independently. Otherwise, the macro identifiers are not replaced. For example:
# Define XYZ This Is A TES
Use the macro printf ("XYZ"); // print "XYZ" without printing "this is a test ". Because the pre-compiler recognizes "XYZ"
? If the string is longer than one row, you can use a backslash '/' At the end of the row to continue the row.
Processor command # errorForced compilation stops compilation, mainly used for program debugging.
# IncludeThe command # I nclude enables the compiler to embed another source file into a source file with # I nclude. The source file to be read must be enclosed by double quotation marks or angle brackets. For example:
# I nclude "stdio. H" or # I nclude
Both lines of code use the C compiler to read and compile subprograms used to process Disk File libraries.
Embedding a file into a file in the # I nclude command is feasible. This method is called nested embedded files. The nested layers depend on the specific implementation.
If the explicit path name is part of the object identifier, search for the embedded object in only the subdirectories. Otherwise, if the file name isDouble quotation marks are enclosed, the current working directory is retrieved first.. If no file is found, search all directories described in the command line. If no file is found, search for the standard directory defined during implementation.
If there is no explicit path name and the file name is enclosed by Angle bracketsCompile the Directory Search in the command line.
If the file is not found, the standard directory is retrieved and the current working directory is not retrieved.
Conditional compilation command
There are several commands to selectively compile each part of the program's source code. This process is called Conditional compilation. Commercial software companies widely use Conditional compilation to provide and maintain many customer versions of a program.
# If, # else, # Elif and # endif
# The general meaning of IF is that if the constant expression after # If is true, the code between it and # endif will be compiled; otherwise, the code will be skipped. Command # endif identifies the end of a # If block.
# If constant-expression
Statement Sequence
# Endif
The expression following # If is evaluated during compilation. Therefore, it must contain only constants and defined identifiers and cannot use variables. The expression does not contain the operator sizeof (sizeof is also a value during compilation ).
# The else command functions a bit like the else in C; # else creates another option (in the case of # If failure ). Note: # else belongs to the # If block.
# The Elif command has the same meaning as the else if command. It forms an if else-If step-by-step statement and supports multiple compilation options. # Elif followed by a constant expression. If the expression is true, the code block after compilation is not tested for other # Elif expressions. Otherwise, test the next part in sequence.
# If expression
Statement Sequence
# Elif expression1
Statement Sequence
# Endif
In nested condition compilation, # endif, # else, or # Elif matches the latest # If or # Elif.
# Ifdef and # ifndef
Another method of Conditional compilation is to use the # ifdef and # ifndef commands, which respectively indicate "if there is a definition" and "if there is no definition ". # The general form of ifdef is:
# Ifdef macroname
Statement Sequence
# Endif
# Ifdef and # ifndef can be used in # If, # else, # Elif statements, but must be used with a # endif.
Command # UNDEF cancel the macro name defined previously. The general format is:
# UNDEF macroname
Command # line changes the content of _ line _ and _ file _They are pre-defined identifiers in the Compilation Program. The basic command format is as follows:
# Line number ["FILENAME"]
The number is a positive integer, and the optional file name is any valid file identifier. The row number is the current row number in the source program, and the file name is the name of the source file. Command # Line is mainly used for debugging and other special applications. Note: The numeric marker after # Line starts from the next row.
Predefined macro name
The ANSI standard specifies the five predefined macro names in C. They are:
_ Line __
_ File __
_ Date __
_ Time __
_ Stdc __
If compilation is not standard, only a few of the above macro names are supported or not supported at all. Remember that the Compilation Program may also provide other predefined macro names.
The _ line _ and _ file _ macro commands have been discussed in the # Line Section. The remaining macro names are discussed here.
The _ date _ 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 _ time _ as a string. String format: minute: second.
If the implementation is standard, macro _ stdc _ contains the decimal constant 1. If it contains any other number, the implementation is non-standard. When compiling a C ++ program, the compiler automatically defines a pre-processing NAME _ cplusplus. When compiling a standard C program, the compiler automatically defines the name _ stdc __.
Note:The macro name is written by an identifier and two underscores (_) on both sides.
(Part of the content from: http://www.bc-cn.net/Article/kfyy/cyy/jc/200511/919.html) 8,
In the C and C ++ macros #,#@,##
Macro,# The function is to stringize macro parameters (stringfication)To put it simply, a double quotation mark is added to the left and right sides of the macro variable referenced by the macro variable.
While# Concatenator)To connect two tokens into one. Note that the connected object is a token, not necessarily a macro variable. For example, you need to create a structure consisting of a menu item command name and a function pointer.