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环境

相关推荐
m0_748240254 分钟前
python轻量级框架-flask
开发语言·python·flask
论迹16 分钟前
【JavaEE】-- 多线程(初阶)2
java·开发语言·java-ee
+72026 分钟前
如何在java中用httpclient实现rpc post 请求
java·开发语言·rpc
web_1553427465634 分钟前
性能巅峰对决:Rust vs C++ —— 速度、安全与权衡的艺术
c++·算法·rust
学习两年半的Javaer35 分钟前
Rust语言基础知识详解【一】
开发语言·rust
PyAIGCMaster36 分钟前
50周学习go语言:第四周 函数与错误处理深度解析
开发语言·学习·golang
9毫米的幻想37 分钟前
【Linux系统】—— 冯诺依曼体系结构与操作系统初理解
linux·运维·服务器·c语言·c++
全栈开发圈37 分钟前
新书速览|Rust汽车电子开发实践
开发语言·rust·汽车
PyAIGCMaster38 分钟前
第二周补充:Go语言中&取地址符与fmt函数详解
开发语言·后端·golang
~kiss~44 分钟前
Rust学习~tokio简介
开发语言·学习·rust