过度使用Pragma Pack(1)

问题描述 投票:1回答:2

是由于过度使用#pragma pack(1)导致填充的原因?后台实际发生了什么?

#pragma pack(1)
typedef struct
{
    union
    {
        uint8_t SAM;
        #pragma pack(1)
        struct {
                uint8_t sm:1;  
                uint8_t sm1:3 ;
                uint8_t sm2 :1 ; 
                uint8_t sm3 :1 ; 
                uint8_t sm4 :1 ;
                uint8_t sm5:1 ; 
            };
          #pragma pack()
        };
}SAM1;
#pragma pack()
c++ c gnu
2个回答
1
投票

您的注释代码:

#pragma pack(1)
// from here on the compiler will align fields on 1 byte
typedef struct
{
    union
    {
        uint8_t SAM;
        #pragma pack(1)
        // there is no use for this pragma on a bit field
        // packing was already at 1 byte
        struct {
                uint8_t sm:1;  
                uint8_t sm1:3 ;
                uint8_t sm2 :1 ; 
                uint8_t sm3 :1 ; 
                uint8_t sm4 :1 ;
                uint8_t sm5:1 ; 
            };
          #pragma pack()
          // from the next struct or union declaration the compiler will use default packing
        };
}SAM1;
#pragma pack()
// from here on the compiler uses default packing

“在看到编译指示后,Package在第一个结构,联合或类声明处生效。”


0
投票

Paul Ogilvieanswer的附加:

#pragma pack()

重新设置为默认值。这甚至可能在某些结构中发生:

#pragma pack(2)
struct S
{
#pragma pack(1)
    char c;
#pragma pack()
    int n; // at default alignment!!!
};
#pragma pack() // without any effect, as set to default already previously

不过,您可以与push / pop结合使用:

#pragma pack(push, 2)
struct S
{
#pragma pack(push, 1)
    char c;
#pragma pack(pop)
    int n; // aligned by 2, as this was set previously
};
#pragma pack(pop) // setting back to what was set before first push in this example

有关更多详细信息,请参见:

https://docs.microsoft.com/en-us/cpp/preprocessor/pack?view=vs-2019

© www.soinside.com 2019 - 2024. All rights reserved.