正如您所说,C++Builder 不支持宏内部的预处理器语句。这记录在 Embarcadero 的网站上:
#define (C++)
在每个单独的宏展开后,都会对新展开的文本进行进一步扫描。这允许嵌套宏的可能性:扩展文本可以包含可以替换的宏标识符。 但是,如果宏扩展为看起来像预处理指令的内容,则预处理器将无法识别该指令。
这是因为宏中的# 字符是为预处理器的字符串化操作符保留的。
包括 MSVC 在内的一些编译器通过 __pragma() 编译器扩展或 C99/C++x0 _Pragma() 扩展来绕过该限制。 C++Builder 的 Windows 32bit 编译器不支持其中任何一个。然而,它的 Windows 64bit 和 mobile 编译器(均基于 clang 并支持 C++11)确实 支持这两者。因此,您可以像这样在宏中添加对这些编译器的支持:
#if defined(__BORLANDC__)
#if defined(__clang__)
#define PACKED_BEGIN __pragma(pack(push, 1))
#define PACKED
#define PACKED_END __pragma(pack(pop))
#else
#error Cannot define PACKED macros for this compiler
#endif
#elif defined(_MSC_VER)
#define PACKED_BEGIN __pragma(pack(push, 1))
#define PACKED
#define PACKED_END __pragma(pack(pop))
#elif defined(__GNUC__)
#define PACKED_BEGIN
#define PACKED __attribute__((__packed__))
#define PACKED_END
#else
#error PACKED macros are not defined for this compiler
#endif
如果你想支持 C++Builder Windows 32bit 编译器,你必须将逻辑移动到使用#pragma 的.h 文件中,然后你可以#include那些需要的文件(至少在编译器更新为支持 clang/C++11 之前 - Embarcadero 目前正在开发):
pack1_begin.h:
#if defined(__BORLANDC__)
#define PACKED_BEGIN
#define PACKED
#define PACKED_END
#pragma pack(push, 1)
#elif defined(_MSC_VER)
#define PACKED_BEGIN __pragma(pack(push, 1))
#define PACKED
#define PACKED_END __pragma(pack(pop))
#elif defined(__GNUC__)
#define PACKED_BEGIN
#define PACKED __attribute__((__packed__))
#define PACKED_END
#else
#error PACKED macros are not defined for this compiler
#endif
pack_end.h:
#if defined(__BORLANDC__)
#pragma pack(pop)
#endif
那么你可以这样做:
#include "pack1_begin.h"
PACKED_BEGIN
struct PACKED {
short someSampleShort;
char sampleByte;
int sampleInteger;
} structType_t;
PACKED_END
#include "pack_end.h"
如果你采用这种方法,你可以完全放弃PACKED_BEGIN/PACKED_END:
pack1_begin.h:
#if defined(__BORLANDC__) || defined(_MSC_VER)
#define PACKED
#pragma pack(push, 1)
#elif defined(__GNUC__)
#define PACKED __attribute__((__packed__))
#else
#error PACKED macro is not defined for this compiler
#endif
pack_end.h:
#if defined(__BORLANDC__) || defined(_MSC_VER)
#pragma pack(pop)
#endif
#include "pack1_begin.h"
struct PACKED {
short someSampleShort;
char sampleByte;
int sampleInteger;
} structType_t;
#include "pack_end.h"