C/C++字节对齐

C/C++字节对齐

C/C++字节对齐

1.G_PACKED

cpp 复制代码
#ifdef __GNUC__
  #define G_PACKED( __Declaration__ ) __Declaration__ __attribute__((packed))
#else
  #define G_PACKED( __Declaration__ ) __pragma( pack(push,1)) __Declaration__ __pragma( pack(pop))
#endif

G_PACKED(
typedef struct __abc
{
    uint8_t  Forced_lock; /*< 数据,赋值操作,*/
    uint32_t  reserve; /*< 数据,赋值操作,预留*/
    uint8_t  hover_now; /*< 数据,赋值操作,*/
}) abc_s;

2.1 pack(push)

cpp 复制代码
#pragma pack(push) //保存对齐状态
#pragma pack(1)//设定为1字节对齐
typedef struct
{
    uint8_t msgType;	//消息类型
    uint16_t exitReason;	//退出原因
} fileTransmitExit_t;
#pragma pack(pop)//恢复对齐状态

2.2 pack(1)

cpp 复制代码
#pragma pack(1) // 按照1个字节对齐
typedef struct
{
    uint8_t msgType;	//消息类型
    uint16_t exitReason;	//退出原因
}fileTransmitExit_t4;
#pragma pack() // 取消自定义对齐方式

全部例子

cpp 复制代码
#pragma once
#include <iostream>

using namespace std;

#ifdef __GNUC__
  #define G_PACKED( __Declaration__ ) __Declaration__ __attribute__((packed))
#else
  #define G_PACKED( __Declaration__ ) __pragma( pack(push,1)) __Declaration__ __pragma( pack(pop))
#endif

G_PACKED(
typedef struct __abc
{
    uint8_t  Forced_lock; /*< 数据,赋值操作,*/
    uint16_t  reserve; /*< 数据,赋值操作,预留*/
    uint8_t  hover_now; /*< 数据,赋值操作,*/
}) test1;

#pragma pack(push) //保存对齐状态
#pragma pack(1)//设定为1字节对齐
typedef struct
{
    uint8_t msgType;	//消息类型
    uint16_t exitReason;	//退出原因
    uint8_t msgType2;
} test2;
#pragma pack(pop)//恢复对齐状态

#pragma pack(1)//设定为1字节对齐
typedef struct
{
    uint8_t msgType;	//消息类型
    uint16_t exitReason;	//退出原因
    uint8_t msgType2;
}test3;
#pragma pack()//恢复对齐状态

typedef struct
{
    uint8_t msgType;	//消息类型
    uint16_t exitReason;	//退出原因
    uint8_t msgType2;
}__attribute__ ((aligned(1))) test4;

typedef struct
{
    uint8_t msgType;	//消息类型
    uint16_t exitReason;	//退出原因
    uint8_t msgType2;
}__attribute__((packed)) test5;

int main()
{
    cout << "Hello World!" << endl;
    printf("test1 size1:%d\n", sizeof (test1));
    printf("test2 size2:%d\n", sizeof (test2));
    printf("test3 size3:%d\n", sizeof (test3));
    printf("test4 size4:%d\n", sizeof (test4));
    printf("test5 size4:%d\n", sizeof (test5));
    return 0;
}

Qt windows 输出结果

ubuntu2004 linux环境

相关推荐
fqbqrr2 分钟前
2510C++,api设计原则,不除零
开发语言·c++
fqbqrr11 分钟前
2510d,C++虚混杂
c++·d
科比不来it27 分钟前
Go语言数据竞争Data Race 问题怎么检测?怎么解决?
开发语言·c++·golang
biter down29 分钟前
c语言14:字符指针
c语言·开发语言
光军oi43 分钟前
JAVA全栈JVM篇————初识JVM
java·开发语言·jvm
给大佬递杯卡布奇诺1 小时前
FFmpeg 基本API av_seek_frame函数内部调用流程分析
c++·ffmpeg·音视频
Moniane1 小时前
C++深度解析:从核心特性到现代编程实践
java·开发语言·jvm
uxiang_blog1 小时前
C++进阶:重载类型转换
linux·开发语言·c++
爱编程的鱼1 小时前
C# 参数详解:从基础传参到高级应用
开发语言·microsoft·c#
Michael_lcf1 小时前
Java的UDP通信:DatagramSocket和DatagramPacket
java·开发语言·udp