About the #pragma preprocessing directives in C + + code

Source: Internet
Author: User
Tags processing instruction

A preprocessing directive is the ability to conditionally skip code Snippets (sections) in the source file, report errors (error messages and line numbers), and warning conditions when the compiler compiles code, as well as describe the different areas of the source code.

Always occupies a single line in the source code, and always begins with the # character and pre-processing instruction name. A white space character can appear in front of the # characters and between the # character and the instruction name.

The following preprocessing directives are available: #define and #undef, respectively, for defining and deselecting conditional compilation symbols. #if, #elif, #else, and #endif to conditionally skip sections in source code. #line, used to control line numbers (used when publishing error and warning messages). #error and #warning, respectively, for issuing errors and warnings. #region and #endregion that are used to explicitly mark sections in the source code. The other is personal, because after all, it's complicated but important. #pragma preprocessor directives

The format is generally: #pragma Para. Where para is the parameter, see some commonly used parameters (from Baidu Encyclopedia)

Message parameter

The message parameter can output the corresponding information in the compilation Information Output window, which is very important for the control of source code information. How to use it:?
1 #pragma message("消息文本")
When the compiler encounters this instruction, it prints the message text in the compilation Output window. When we define a number of macros in the program to control the source code version, it is possible for us to forget that we have the correct settings for these macros, and we can use this instruction to check at compile time. Suppose we want to determine if we have defined the _x86 in the source code where the macro can be used in the following way?
123 #ifdef _X86#pragma message("_X86 macro activated!")#endif
When we define the _x86 macro, the application will be compiled with the "_x86 macro activated!" displayed in the Compile Output window. ”。 We will not scratching because we do not remember some of the specific macros we have defined.code_segAnother pragma parameter that is used more is code_seg. Format such as:?
1 #pragma code_seg(["section-name"[,"section-class"]])
It is able to set the code snippet where the function code is stored in the program, which is used when we develop the driver.#pragma once(more commonly used) as long as the header file at the beginning of this directive will be able to ensure that the header file is compiled once, this instruction is actually in the VC6, but considering the compatibility is not much use of it. #pragma once is a compilation-related, that is, this compilation system can be used, but in other compiled systems may not be, that is, the transplant is poor, but now basically every compiler has this definition. #ifndef, #define, #endif这个是C + + language-related, which is a macro definition in the C + + language that avoids multiple compilations of files through macro definitions. So it works on all compilers that support the C + + language, and it's best to use this approach if you're writing programs that cross-platform#pragma hdrstop#pragma hdrstop indicates that the precompiled header file ends, and the subsequent header files are not precompiled. BCB can precompile the header file to speed up the link, but if all the header files are precompiled and may take up too much disk space, use this option to exclude some header files. Sometimes there are dependencies between units, such as cell A depends on unit B, so unit B is compiled before unit A. You can use #pragma startup to specify the compilation priority, and if you use the #pragma package (smart_init), the BCB will be compiled according to the priority size.#pragma resource#pragma resource "*.DFM" indicates that the resources in the *.DFM file are added to the project. The *.DFM includes the definition of the form's appearance.#pragma warning?
1 #pragma warning(disable:450734;once:4385;error:164)
Equivalent to:?
123 #pragma warning(disable:450734)//不显示4507和34号警告信息#pragma warning(once:4385)//4385号警告信息仅报告一次#pragma warning(error:164)//把164号警告信息作为一个错误。
At the same time this pragma warning also supports the following format:?
12 #pragma warning(push[,n])#pragma warning(pop)
Here n represents a warning level (1---4).
123 #pragma warning(push)保存所有警告信息的现有的警告状态。#pragma warning(push,n)保存所有警告信息的现有的警告状态,并且把全局警告等级设定为n。#pragma warning(pop)向栈中弹出最后一个警告信息,
All changes made between the stack and the stack are canceled. For example:?
123456 #pragma warning(push)#pragma warning(disable:4705)#pragma warning(disable:4706)#pragma warning(disable:4707)//.......#pragma warning(pop)
At the end of this code, all warning messages (including 4705,4706 and 4707) are re-saved.pragma comment?
1 #pragma comment(...)
This directive places a note record into an object file or executable file. The commonly used LIB keyword can help us to connect to a library file. Each compiler can use the #pragma directive to activate or terminate some of the compilation features supported by the compiler. For example, for the Loop optimization feature:?
12 #pragma loop_opt(on)//激活#pragma loop_opt(off)//终止
Sometimes, there are some functions in the program that will cause the compiler to send you familiar and want to ignore the warning, such as "Parameter xxx is never used in function xxx", can this:?
1234 #pragma warn—100//Turnoffthewarningmessageforwarning#100intinsert_record(REC*r){/*functionbody*/}#pragma warn+100//Turnthewarningmessageforwarning#100backon
The function generates a warning message with a unique signature of 100, so that the warning can be temporarily terminated. Each compiler has a different implementation of #pragma, which is effectively in a compiler that is almost invalid in another compiler. Can be viewed from the compiler's documentation.
123456 #pragma pack(n)和#pragm apop()structsample{char a;doubleb;};
When the sample structure does not have #pragma pack (n), the sample is aligned to the largest member; (the so-called alignment is when the alignment number is n, each member is aligned, and if the size of member A is less than N, a expands to n size; If the size of a is greater than N, the size of a is used, so the size of the above structure is 16 bytes. When the sample structure is added #pragma pack (1), sizeof (sample) = 9 bytes; no null bytes. (Note: When n is greater than the size of the largest member of the sample structure, n takes the maximum member size.) So when n is larger, the faster the structure, the larger the size, and vice versa #pragma pop () is the meaning of canceling the #pragma pack (n), which means that the next structure is not #pragma pack (n)?
1 #pragma comment(comment-type,["commentstring"])
Comment-type is a predefined identifier that specifies the type of annotation and should be one of the compiler,exestr,lib,linker. Comment String is a string that provides additional information for Comment-type. Note type: 1, compiler: Place compiler version or name to an object file, this option is ignored by linker. 2, Exestr: In the future version will be canceled. 3, Lib: Put a library search records into the object file, this type should be and comment string (Specify the name and path of the lib you want to linker search) The name of this library is placed behind the default library search record of the object file. Linker Search This library as you would enter this command at the command line. You can set up multiple library records in one source file, in the same order in the object file as in the source file. If the order of the default libraries and additional libraries is different, the z-compile switch is used to prevent the default libraries from being placed into the object module. 4. Linker: Specify a connection option so that it does not have to be entered in the command line or set in the development environment. Only the following linker option can be passed to linker.
1 /DEFAULTLIB,/EXPORT,/INCLUDE,/MANIFESTDEPENDENCY,/MERGE,/SECTION
(1) The/DEFAULTLIB:LIBRARY/DEFAULTLIB option adds a library to the list of libraries that LINK searches for when resolving references. The library specified by/defaultlib is searched after the library specified on the command line and the default library specified in the. obj file. Override/defaultlib:library for all default library (/NODEFAULTLIB) options. If you specify the same library name in both, omit the library (/nodefaultlib: Library) option overrides the/defaultlib: Library。 (2)/export: EntryName[,@ ordinal[, NONAME]] [, DATA] uses this option to export a function from a program so that other programs can call the function. You can also export data. Exports are typically defined in a DLL. EntryNameis the name of the function or data item to be used by the calling program. ordinal specifies an index of 1 to 65,535 in the export table, and if no ordinal is specified, LINK assigns one. NONAMEThe keyword only exports the function as an ordinal, without EntryNameDATAkeyword Specifies that the exported item is a data item. The data items in the client program must be extern __declspec (dllimport)To declare. There are three ways to export definitions, followed by the recommended order of use: __declspec in source code (dllexport). def file in the exports statement in the/EXPORT specification in the link command all three methods can be used in the same program. LINK also creates an import library when the program that contains the export is generated, unless the. exp file is used in the build. LINK uses the decorated form of an identifier. The compiler modifies the identifier when creating the. obj file. If EntryNameis assigned to the linker in its unmodified form (as in the source code), link attempts to match the name. If a unique matching name cannot be found, LINK issues an error message. When you need to assign an identifier to the linker, use the Dumpbin tool to get the decorated name of the identifier. (3) The/include:symbol/include option notifies the linker to add the specified symbol to the symbol table. To specify multiple symbols, type a comma (,), semicolon (;)) between the symbol names. or spaces. On the command line, specify/include:symbol once for each symbol. The linker parses the symbol by adding the object that contains the symbol definition to the program. This feature is useful for adding library objects that are not linked to a program. Use this option to specify that the symbol will override the removal of the symbol through/OPT:REF. We often use this kind of #pragma comment (lib, "*.lib"). #pragma comment (lib, "ws2_32.lib") means that the link ws2_32.lib this library. And in the project Setup to write a link into the ws2_32.lib effect, but this method of writing the program others in the use of your code when you do not have to set up the project settings#pragma disableDeclared before a function, valid only for one function. The function call will not be interrupted in the process. Generally used in the C51 more.#pragma data_segIntroduction [1] using #pragma data_seg to create a new data segment and define shared data, in the specific format:?
123 #pragma data_seg("shareddata")HWNDsharedwnd=NULL;//共享数据#pragma data_seg()
-----------------------------------------------------------------1, #pragma data_seg () is generally used in DLLs. In other words, a shared named data segment is defined in the DLL. The key is that the global variables in this data segment can be shared by multiple processes, or the global variables in the DLL cannot be shared between multiple processes. 2, the shared data must be initialized, otherwise the Microsoft compiler will put the data that is not initialized. BSS segment, resulting in shared behavior between multiple processes failing. For example?
123456789101112 #pragma  data_ SEG ("MyData") intg_value; //notethattheglobalisnotinitialized. #pragma  data_seg () //dll provides two interface functions: int  getvalue () {      return  g_value; } void   SetValue ( int  n) {      g_value=n;
Then start two processes A and b,a and b all call this DLL, if a calls the SetValue (5); b then call int m = GetValue (); Then the value of M is not necessarily 5, but an undefined value. Because the global data in the DLL is private and cannot be shared for each process that invokes it. If you initialize the G_value, the G_value will surely be placed in the MyData section. In other words, if a calls the SetValue (5); b then call int m = GetValue (); Then the value of M must be 5, which enables data communication across processes.#pragma Region#pragma region is a preprocessing directive specific to Visual C + +. It allows you to fold specific blocks of code, making the interface cleaner and easier to edit other code. The collapsed code block does not affect compilation. You can also expand the code block at any time to make edits, and so on. Format:?
1 #pragma region name#pragma endregion comment
Use the following example:?
123456789 #pragma  region variables   HWND  HWND;  const  size_t  MAX_LENGTH = 20;  //other variables   #pragma  endregion this region contains global variables.
As shown above, the code that needs to be collapsed must be contained between #pragma region and #pragma endregion. After you #pragma region and #pragma endregion, you can add some text to annotate. When you collapse a block of code, the text appears in the collapsed position. Ways to collapse code blocks: As in Visual C + +, when you collapse a function, class, namespace, and when the code is contained between the instructions described above, a "-" sign appears to the left of the line #pragma region, click to collapse the content, and the "-" sign becomes the "+" sign. Click again to expand the code block. This precompiled directive is available in Visual Studio 2005 and later. However, in Visual Studio 2005, when #pragma region contains text similar to "1st", it can cause "error c2059:syntax error: ' Bad suffix on Number '" compilation error. Avoiding the use of numbers or separating numbers from letters can solve this problem. [2]Application Example (#pragma pack)In network protocol programming, data packets of different protocols are often processed. One way is to get a variety of information through the method of pointer offset, but it is not only complicated programming, and once the protocol changes, the program will be more cumbersome to modify. After understanding the compiler's principle of allocation of structure space, we can use this feature to define our own protocol structure, and access the members of the structure to obtain various information. This not only simplifies programming, but even if the protocol changes, we only need to modify the definition of the protocol structure, other programs without modification, save time and effort. The following is an example of the TCP protocol header, which describes how to define the protocol structure. Its protocol structure is defined as follows:?
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + #pragma pack(1)//按照1字节方式进行对齐struct TCPHEADER{shortSrcPort;//16位源端口号shortDstPort;//16位目的端口号intSerialNo;//32位序列号intAckNo;//32位确认号unsignedcharHaderLen:4;//4位首部长度unsignedcharReserved1:4;//保留16位中的4位unsignedcharReserved2:2;//保留16位中的2位unsignedcharURG:1;unsignedcharACK:1;unsignedcharPSH:1;unsignedcharRST:1;unsignedcharSYN:1;unsignedcharFIN:1;shortWindowSize;//16位窗口大小shortTcpChkSum;//16位TCP检验和shortUrgentPointer;//16位紧急指针};#pragm apop()//取消1字节对齐方式
#pragma the alignment length specified by the pack, the actual rules used are: struct, union, or data member of the class, the first place is placed at offset 0, and subsequent alignment of each data member, in accordance with the value specified by #pragma pack and the length of the data member itself, is smaller than the lesser one. However, when the value of the #pragma pack is equal to or exceeds the length of the longest data member, the size of the value will have no effect. And the structure of the whole alignment, then according to the structure of the largest data members.

About the #pragma preprocessing directives in C + + code

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.