Linux # pragma usage

Source: Internet
Author: User
Precompiled command # pragma usage

Recently, when I was looking at the code in an open-source project, I found that the # pragma program was used in many places. Therefore, I asked a Google instructor and summarized the common usage of the # pragma pre-compilation command. I would like to share with you now.

I. # The most common Pragma method 1. # progma pack (n) 1> functions:

Using the # progma pack pre-compiled command can change the default value of the compiler (not absolute, Some compilers can only be fixed Data Alignment ).

2> description

In most cases, alignment is not taken into account when writing a program, because the compiler selects the correct policy for us. Most compilers use the default four-byte alignment mode.

You can read a program to understand:

Program:

# Include <stdio. h>

Struct

{

Int;

Char B;

Short C;

};

Int main ()

{

Int D;

D = sizeof (struct );

Printf ("theleng = % d \ n", d );

Return 0;

}

Note:

(1) generally, we use a 32-bit processor. The default alignment byte Number of the VC compiler is 4 bytes. By default, GCC uses the largest type of variable in the struct as the byte alignment.

Struct a contains a four-byte int, a one-byte char, and a two-byte short data. Therefore, the space used by a is 7 bytes. However, the compiler must align the data members in space. Therefore, the sizeof (strcut a) value is 8. A occupies 4 bytes, B occupies 1 byte, and C occupies 2 bytes. Therefore, the compiler will put B and C within a 4 byte, so struct a occupies 8 bytes

(2) Now we will discuss the advantages of byte alignment:

In modern computers, memory space is divided by byte. Theoretically, it seems that access to any type of variables can start from any address, however, the actual situation is that access to specific variables is often performed at specific memory addresses, which requires various types of data to be arranged in space according to certain rules, instead of sequential emissions, this is alignment.

 

Alignment functions and causes: the processing of storage space varies greatly by hardware platform. Some platforms can only access certain types of data from some specific addresses. This may not be the case for other platforms, but the most common problem is that data storage alignment is not in line with the requirements of their platforms, which may cause a loss of access efficiency.

 

For example, some platforms start from the even address each time they read data. If an int type (assuming a 32-bit System) is stored at the beginning of the even address, a read cycle can be read, if the data is stored at the beginning of the odd address, it may take two read cycles and splice the high and low bytes of the two read results to obtain the int data. Obviously, reading efficiency is greatly reduced. This is also a game of space and time.

3> how to use?

Example:
# Pragma pack (push) // Save the previous alignment status. Push pushes the previous alignment status to the stack.
# Pragma pack (1) // specify the new alignment state, 1 byte
// Define your structure
//............
# Pragma pack (POP) // the pop-up stack to restore the previous alignment

Now let's modify the program:

Program B:

# Include <stdio. h>

 

# Pragma pack (push)

# Pragma pack (1)

 

Struct

{

Int;

Char B;

Short C;

};

# Pragma pack (POP );

Int main ()

{

Int D;

D = sizeof (struct );

Printf ("theleng = % d \ n", d );

Return 0;

}

In this case, a occupies a total of 7 bytes because it is aligned by one byte.

2. # pragma message ("String constant ")

1> functions:

When the compiler encounters this instruction, it prints the message text in the compilation output window.

2> note:

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.

3> how to use?
# Pragma message ("macro activated !")

Note: No extra points are added after message.

3. # pragma once

1> functions:

You only need to add this command at the beginning of the header file to ensure that the header file is compiled once.

2> Note: # difference between Pragma once and # ifndef

(1) similarities:

To prevent the same file from being included multiple times, # ifndef and # pragma once (provided that the compiler supports both methods ), there is no big difference between the two.

(2) Use of the two methods:

Method 1:

# Ifndef _ tiger_h __

# DEFINE _ tiger_h __

.......... // Some declaration statements

# Endif

Method 2:

# Pragma once

......... // Some declaration statements

(3) differences between the two:

# The ifndef method depends on the macro name and cannot conflict with each other. This not only ensures that the same file is not included multiple times, but also ensures that the two header files with identical content are not accidentally included at the same time. Of course, the disadvantage is that if the macro names of different header files are accidentally "crashed", the header files may obviously exist, but the compiler cannot find the declaration.

# Pragma once is guaranteed by the compiler: the same file will not be contained multiple times. Note that the same file here refers to a physical file, not two files with the same content. The benefit is that you don't have to think about a macro name any more, and of course there will be no strange problems caused by the macro name collision. The disadvantage is that if a header file has multiple copies, this method cannot ensure that it is not repeatedly included. Of course, repeat inclusion is easier to detect and correct than the "no declaration found" problem caused by macro name collision.

For # pragmaonce, according to The msdn explanation, it can prevent a file from being contained multiple times. Compared with file protection in the form of # ifndef # define # endif, the former is platform-related and has poor portability, but is more efficient because it does not need to open the contained files, you can determine whether the file is contained. Of course, this work is done by the system for us. The latter has the advantage that it is a language-related feature, so it has good portability. However, when a file is contained, you only need to open the file and determine whether the file has been included based on whether the file's protection macro has been defined. Relatively low efficiency. Of course, when # include is used, the programmer can determine whether the protection macro of the file to be included has been defined to determine whether to include the file. Similar to the following code:

# Ifndef file_h _

# Include "file. H"

# Endif

In this way, high efficiency can be achieved and portability can be ensured. However, the dependency between files is high. If a file's Macro Protection changes, all files that use the above form to include this file must be modified. It is against the idea of modularization.

Ii. # other Pragma methods 1. # The Pragma parameter is code_seg.

1> Format:

# Pragma code_seg ([[{push | Pop},] [identifier,] ["segment-name" [, "segment-class"])

2> functions:

It can set the code segment where function code is stored in the program. It is used when we develop the driver.

3> note:

This command is used to specify the function in. the section in the OBJ file. observe that the OBJ file can use the dumpbin command line program provided by VC. the default Storage section of the OBJ file is. text section. If code_seg does not contain parameters, the function is stored in. text section. Push (optional parameter) places a record in the stack of the internal compiler. Optional parameters can be an identifier or a node name. Pop (optional parameter) pops up a record from the top of the stack. This record can be an identifier or a node name. Identifier (optional parameter) an identifier assigned to the record that is pushed into the stack when the push command is used. When the identifier is deleted, the record in the stack associated with it is popped up. "Segment-name" (optional) indicates the node name stored by the function.

3> instance:

// By default, functions are stored in. Text.

Void func1 () {// stored in. Text

}

 

// Store the function in. my_data1

# Pragma code_seg (". my_data1 ")

Void func2 () {// stored in my_data1

}

 

// R1 is the identifier. Put the function in. my_data2.

# Pragma code_seg (push, R1, ". my_data2 ")

Void func3 () {// stored in my_data2

}

 

Int main (){

}

2. # pragma hdrstop

1> functions:

Indicates that the header file is pre-compiled till now, and the header file is not pre-compiled. BCB can pre-compile the header file to speed up the link, however, if all header files are pre-compiled, it may occupy too much disk space. Therefore, use this option 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.
3. # pragma warning

1> functions:

This command allows you to selectively modify the warning messages of the compiler.

2> command format:

# Pragma warning (warning-specifier: Warning-number-list [; warning-specifier: Warning-number-list...]

# Pragma warning (push [, N])

# Pragma warning (POP)

3> the main warnings are as follows:

Once: only display once (warning/error) Message

Default: resets the warning behavior of the compiler to the default state.

1, 2, 3, 4: four warning levels

Disable: Disable specified warning information

Error: uses the specified warning information as an error report.

If you are not quite familiar with the above explanation, you can refer to the example and description below in the examples.

# Pragma warning (Disable: 4507 34; once: 4385; error: 164)

It is equivalent:

# Pragma warning (Disable: 4507 34) // do not display the 4507 and 34 Warnings

# 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 global warning

The level is set to n.

# Pragma warning (POP) pops up the last warning message to the stack.

All changes 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)

Many warning messages are often generated when standard C ++ is used for programming, and these warning messages are unnecessary prompts,

So we can use # pragma warning (Disable: 4786) to disable this type of warning.

When using ADO in VC, we will also get unnecessary warning information.

# Pragma warning (Disable: 4146) to eliminate this type of warning information

4. # pragma comment (...)

1> functions:

This command puts a comment record into an object file or executable file.

2> Format:

# Pragma comment ("comment-type" [, commentstring])

Comment-type: either of the five predefined identifiers can be specified.

Five predefined identifiers are:

(1) compiler: puts the version number and name of the compiler into the target file. This comment record will be ignored by the compiler. If you provide the commentstring parameter for this record type, the compiler generates a warning.

Example: # pragma comment (compiler)

(2) exestr: Put the commentstring parameter in the target file. During the link, this string will be placed in the executable file. When the operating system loads the executable file, the parameter string is not loaded into the memory. however, this string can be searched and printed by programs such as dumpbin. You can use this identifier to embed version numbers and other information into the executable file!

(3) Lib: This is a very common keyword used to link a library file to the target file.

Common lib keywords can help us to connect to a library file.

For example:

# Pragma comment (Lib, "user32.lib ")

This command is used to add the user32.lib library file to this project.

Linker: place a link option in the target file. You can use this command to replace the commands passed in by the command line or in the development environment.

You can specify the/include option to forcibly include an object. For example:

# Pragma comment (linker, "/include :__ mysymbol ")

You can set the following link options in the program

/Defaultlib

/Export

/Include

/Merge

/Section

These options are not described here. For details, refer to msdn!

5. # pragma resource "*. DFM"

1> functions:

Add the resources in the *. DFM file to the project. *. DFM defines the appearance of a form.

 

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.