매크로 정 의 를 이용 하여 컴 파일 단계 에서 구조 체 크기 를 검사 하 는 방법

2726 단어 구조 체
http://blog.csdn.net/crazycoder8848/article/details/8292770
=====================================================
typedef struct
{
    char a[100];
} T_XXX;

typedef struct
{
    char a[99];
} T_QQQ;

 

/*                 */
#define    SIZE_OF_TYPE_EQUAL_TO(type, size) \
static inline char size_of_##type##_equal_to_##size() \
{ \
    char __dummy1[sizeof(type) - size]; \
    char __dummy2[size - sizeof(type)]; \
    return __dummy1[-1] + __dummy2[-1]; \
}

 

/*                  */
#define    SIZE_OF_TYPE_UNEQUAL_TO(type, size) \
static inline char size_of_##type##_unequal_to_##size() \
{ \
    char __dummy1[0==(10/(sizeof(type)-size))]; \
    return __dummy1[-1]; \
}

 

/*                  */
#define    SIZE_OF_TYPE_NOT_LARGER_THAN(type, size) \
static inline char size_of_##type##_not_larger_than_##size() \
{ \
    char __dummy1[size - sizeof(type)]; \
    return __dummy1[-1]; \
}

 

/*                  */
#define    SIZE_OF_TYPE_NOT_SMALLER_THAN(type, size) \
static inline char size_of_##type##_not_smaller_than_##size() \
{ \
    char __dummy1[sizeof(type) - size]; \
    return __dummy1[-1]; \
}

 

/*                 */
#define    SIZE_OF_TYPE_SMALLER_THAN(type, size) \
    SIZE_OF_TYPE_NOT_LARGER_THAN(type, size) \
    SIZE_OF_TYPE_UNEQUAL_TO(type, size)

 

/*                 */
#define    SIZE_OF_TYPE_LARGER_THAN(type, size) \
    SIZE_OF_TYPE_NOT_SMALLER_THAN(type, size) \
    SIZE_OF_TYPE_UNEQUAL_TO(type, size)

 

/*                   2 */
#define    SIZE_OF_TYPE_SMALLER_THAN2(type, size) \
static inline char size_of_##type##_smaller_than2_##size() \
{ \
    char __dummy1[size - sizeof(type) - 1]; \
    return __dummy1[-1]; \
}

 

/*                   2 */
#define    SIZE_OF_TYPE_LARGER_THAN2(type, size) \
static inline char size_of_##type##_larger_than2_##size() \
{ \
    char __dummy1[sizeof(type) - size - 1]; \
    return __dummy1[-1]; \
}

 

/*                    */
#define    SIZE_OF_TYPE_IS_MULTIPLE_OF(type, size) \
static inline char size_of_##type##_is_multiple_of_##size() \
{ \
    char __dummy1[0 - (sizeof(type) % size)]; \
    return __dummy1[-1]; \
}

/***
      ,    ,     ,        。
               ,      。
      ,     ,          :-)
***/
SIZE_OF_TYPE_EQUAL_TO(T_XXX, 100)
SIZE_OF_TYPE_UNEQUAL_TO(T_XXX, 99)
SIZE_OF_TYPE_NOT_LARGER_THAN(T_XXX, 100)
SIZE_OF_TYPE_NOT_SMALLER_THAN(T_QQQ, 98)
SIZE_OF_TYPE_LARGER_THAN(T_QQQ, 96)
SIZE_OF_TYPE_SMALLER_THAN(T_QQQ, 200)

SIZE_OF_TYPE_LARGER_THAN2(T_QQQ, 96)
SIZE_OF_TYPE_SMALLER_THAN2(T_QQQ, 200)
SIZE_OF_TYPE_IS_MULTIPLE_OF(T_QQQ, 9)

 

int main()
{
    return 0;
}

좋은 웹페이지 즐겨찾기