Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct size alignment

I want the size of a C struct to be multiple of 16 bytes (16B/32B/48B/..). It does not matter which size it gets to; it only needs to be multiple of 16 bytes.

How could I enforce the compiler to do that?

like image 606
Neo Hpcer Avatar asked Jun 21 '12 00:06

Neo Hpcer


1 Answers

For Microsoft Visual C++:

#pragma pack(push, 16)

struct _some_struct
{
     ...
}

#pragma pack(pop)

For GCC:

struct _some_struct { ... } __attribute__ ((aligned (16)));

Example:

#include <stdio.h>

struct test_t {
    int x;
    int y;
} __attribute__((aligned(16)));

int main()
{
    printf("%lu\n", sizeof(struct test_t));
    return 0;
}

compiled with gcc -o main main.c will output 16. The same goes for other compilers.

like image 88
vharavy Avatar answered Oct 16 '22 00:10

vharavy