下面的代码片段,我们如何让下面的结构定义为 4 字节对齐?
我已经尝试过 pragma pack
来显式对齐。但是它没有像我们想要的那样工作...
#pragma pack(push)
#pragma pack(4)
//..struct devine here.
#pragma pack(pop);
我已尝试将 __attribute__
显式对齐。它也不起作用..
struct device_info {
//
}__attribute__(packed);
//struct device_info dev_info;
sizeof (struct device_info)=211
我已尝试将 __attribute__
显式对齐。它也不起作用..
struct device_info {
//
};
typedef struct device_info deice_info __attribute__(packed)
device_info dev_info;
sizeof (dev_info)=211
问题1:
如何显式对齐 struct device_info
,并输出如下所示的 offsetof
:
offsetof magic=0
offsetof is_unlocked=16
offsetof is_tampered=20
offsetof is_unlock_critical=24
offsetof charger_screen_enabled=28
offsetof display_panel=32
offsetof booloader_version=96
offsetof radio_version=160
offsetof verity_mode=224
offsetof is_origin=228
代码片段:
#define DEVICE_MAGIC_SIZE 13
#define MAX_PANEL_ID_LEN 64
#define MAX_VERSION_LEN 64
struct device_info{
unsigned char magic[DEVICE_MAGIC_SIZE];
bool is_unlocked;
bool is_tampered;
bool is_unlock_critical;
bool charger_screen_enabled;
char display_panel[MAX_PANEL_ID_LEN];
char booloader_version[MAX_VERSION_LEN];
char radio_version[MAX_VERSION_LEN;
bool verity_mode;
bool is_origin;
};
更新 1
我试过下面的片段
struct device_info{
__attribute__((__aligned(4))) bool is_unlock;
//...
};
效果好是一样的。
问题二:
有什么区别
struct device_info{
__attribute__((__aligned(4))) bool is_unlock;
//...
};
和
struct device_info{
bool is_unlock;
//..
}__attribute__((__aligned(4))) ;
问题三
我们如何在编译执行二进制或库的源代码期间转储?(预处理->编译->链接)objdump?或其他?
最佳答案
从 C11 开始,您可以使用标准 alignas specifier . 这应该可以解决您的问题。
关于c - 如何将结构显式对齐为 4 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894720/