Programming

“__attribute __ ((packed, align (4)))”의 의미는 무엇입니까

procodes 2020. 7. 21. 21:45
반응형

“__attribute __ ((packed, align (4)))”의 의미는 무엇입니까


C 언어이며 다음과 같이 작성됩니다.

typedef struct __attribute__((packed, aligned(4))) Ball {
    float2 delta;
    float2 position;
    //float3 color;
    float size;
    //int arcID;
    //float arcStr;
} Ball_t;
Ball_t *balls;

그 의미가 무엇인지,이 키워드를 사용하는 방법을 알려주십시오.


대답하기 전에 Wiki의 데이터를 드리고자합니다.


데이터 구조 정렬 은 컴퓨터 메모리에서 데이터가 배열되고 액세스되는 방식입니다. 데이터 정렬데이터 구조 패딩 이라는 두 가지 별도의 관련 문제로 구성됩니다 .

최신 컴퓨터가 메모리 주소를 읽거나 쓸 때 워드 크기의 청크 (예 : 32 비트 시스템의 4 바이트 청크)로이 작업을 수행합니다. 데이터 정렬 은 데이터를 워드 크기의 배수와 같은 메모리 오프셋에 배치 하는 것을 의미하며, 이는 CPU가 메모리를 처리하는 방식으로 인해 시스템 성능을 향상시킵니다.

데이터를 정렬하려면 마지막 데이터 구조의 끝과 다음 데이터의 시작 사이에 의미없는 바이트를 삽입해야합니다 ( 데이터 구조 패딩) .


gcc는 구조 패딩을 비활성화하는 기능을 제공합니다. 즉, 경우에 따라 이러한 의미없는 바이트를 피하기 위해. 다음 구조를 고려하십시오.

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct)구조 패딩으로 인해 8이 아닌 12가됩니다. 기본적으로 X86에서 구조는 4 바이트 정렬로 채워집니다.

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

__attribute__((packed, aligned(X)))특정 (X) 크기의 패딩을 주장 하는 사용할 수 있습니다 . X는 2의 거듭 제곱이어야합니다. 여기를 참조 하십시오

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

따라서 위에서 지정한 gcc 속성은 구조 패딩을 허용하지 않습니다. 크기는 8 바이트입니다.

모든 구조에 대해 동일한 작업을 수행하려면 다음을 사용하여 정렬 값을 스택으로 푸시하면됩니다. #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.


The attribute packed means that the compiler will not add padding between fields of the struct. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.

aligned(4) means that the struct should be aligned to an address that is divisible by 4.

참고URL : https://stackoverflow.com/questions/11770451/what-is-the-meaning-of-attribute-packed-aligned4

반응형