简体   繁体   中英

How can I aligned struct as 4 bytes expicitly

below code snippet,How can we make below struct define as 4 bytes aligned?

I have tried pragma pack to aligned Explicitly.But It's does NOT work as we want...

#pragma pack(push)
#pragma pack(4)
//..struct devine here.
#pragma pack(pop);

I have tried __attribute__ to aligned Explicitly.It's also does NOT work as well..

struct device_info {
    //
}__attribute__(packed);
//struct device_info dev_info;
sizeof (struct device_info)=211

I have tried __attribute__ to aligned Explicitly.It's also does NOT work as well..

struct device_info {
    //
};
typedef struct device_info deice_info __attribute__(packed)
device_info dev_info;
sizeof (dev_info)=211

Question1:

How can I aligned struct device_info Explicitly,and offsetof output like below:

    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

code snippet:

#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;
};

Update 1

I have tried below snippet

struct device_info{
    __attribute__((__aligned(4))) bool is_unlock;
    //...
};

It's same that work well.

Question two:

What's difference between

struct device_info{
    __attribute__((__aligned(4))) bool is_unlock;
    //...
};

and

struct device_info{
    bool is_unlock;
    //..
}__attribute__((__aligned(4))) ;

Question 3

How can we dump during source code compiled to execute binary or library?(preprocessing->Compile->link) objdump?or others?

Since C11 you can use the standard alignas specifier . This should solve your question.

It would appear that in your implementation, sizeof(bool) is equal to 1. In that case, the padding rules are being correctly adhered to, so is_unlocked can appear precisely after magic with no additional padding.

The other thing is that bool is implementation-defined. Please read this post: Is sizeof(bool) defined?

What you might benefit more from, is to use proper types from <ctype.h> when you are laying out a structure with absolute sizes. If you want your bool values to be 32-bit integers, then use int32_t or uint32_t instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM