收到有关压缩结构的意外编译警告

Got unexpected compile warning about packed structure

本文关键字:意外 编译 警告 结构 压缩      更新时间:2023-10-16

当我运行以下代码片段时,收到了警告,不知道为什么。g++的版本为4.8.4。

$ g++ -g  -fPIC -std=c++11 -fpermissive te.cc
te.cc:25:11: warning: ignoring packed attribute because of unpacked non-POD field ‘cMacAddr strArp::src_hw_mac’ [enabled by default]
  cMacAddr src_hw_mac;
           ^
te.cc:27:11: warning: ignoring packed attribute because of unpacked non-POD field ‘cMacAddr strArp::dst_hw_mac’ [enabled by default]
  cMacAddr dst_hw_mac;

代码段"te.cc"

#include <iostream>
#include <utility>
#include <functional>
#include <string>
using namespace std;
typedef unsigned char uchar;
typedef unsigned short uint16;
typedef unsigned int uint;
char _ethHdrPrintBuf[100];
class cMacAddr {
public:
    uchar addr[6];
    cMacAddr() { for (int i=0; i<6; i++) addr[i] = 0;}
};
struct strArp {
    uint16 hw_type;
    uint16 proto_type;
    uchar  hw_size;
    uchar  proto_size;
    uint16 opcode;
    cMacAddr src_hw_mac;
    uint  src_proto_ipv4;
    cMacAddr dst_hw_mac;
    uint  dst_proto_ipv4;
} __attribute__((__packed__ )) ;
int main()
{
    cout << sizeof(strArp) << endl;
    return 0;
}

cMacAddr有一个构造函数,因此它不能是POD。这里的细节太多了。