__attribute__

__attribute__

1.__attribute__ ((attribute-list))

The __attribute__ keyword is mainly used to set its attributes in a function or data declaration.

The main purpose of assigning attributes to functions is to allow the compiler to optimize.

For example: __attribute__((noreturn)) in the function declaration is to tell the compiler that this function will not be returned to the caller, so that the compiler can remove unnecessary function return codes during optimization.

2. __attribute__ ((packed))

Let the compiler cancel the optimized alignment of the structure during the compilation process, and align it according to the actual number of bytes occupied. In this way, both sides need to use __attribute__ ((packed)) to cancel the optimized alignment, and there will be no alignment misalignment.

 

#include <stdio.h>

typedef struct TEST
{
    char a;
    int b;
} test;


int main(void)
{
    printf("sizeof()=%d.\n",sizeof(test));
    return 0;
}

The output is: 8

#include <stdio.h>

typedef struct TEST
{
    char a;
    int b;
}__attribute__((packed)) test;


int main(void)
{
    printf("sizeof()=%d.\n",sizeof(test));
    return 0;
}

output: 5

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325367726&siteId=291194637