在(旧的)Linux 源代码(用 C89 编写)中,出现了一个 #define
,它用作结构初始化中的文字 (ide_pci_device_s
)使用标准的 C89 struct literal initializer 语法,但是,当我使用支持 C99 的编译器进行编译时,出现错误 initializer element is not constant
,下面是我正在使用的代码示例抛出错误。
#define ON_BOARD 1
#define PCI_VENDOR_ID_INTEL 0x8086
#define PCI_DEVICE_ID_INTEL_82371FB_0 0x122e
#define DEVID_PIIXa ((ide_pci_devid_t){PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371FB_0})
typedef char byte;
typedef struct ide_pci_devid_t {
int one, two;
} ide_pci_devid_t;
typedef struct ide_hwif_t {
int whatever;
} ide_hwif_t;
typedef struct ide_pci_enablebit_s {
byte reg; /* byte pci reg holding the enable-bit */
byte mask; /* mask to isolate the enable-bit */
byte val; /* value of masked reg when "enabled" */
} ide_pci_enablebit_t;
typedef struct ide_pci_device_s {
ide_pci_devid_t devid;
const char *name;
void (*init_hwif)(ide_hwif_t *hwif);
ide_pci_enablebit_t enablebits[2];
byte bootable;
unsigned int extra;
} ide_pci_device_t;
static ide_pci_device_t ide_pci_chipsets[] = {
// HERE is where it says 'non-const initializer
{DEVID_PIIXa, "PIIX", NULL, {{0x41,0x80,0x80}, {0x43,0x80,0x80}}, ON_BOARD, 0 },
};
如何在最小程度地改变源代码的结构以使用 C99 编译器构建的同时仍然使用 #define
的值?
最佳答案
问题是 Actor :
#define DEVID_PIIXa ((ide_pci_devid_t){PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371FB_0})
您的编译器认为这使它成为非常量。由于您使用初始化程序的地方正在初始化嵌套的 ide_pci_devid_t
结构,因此您不需要强制转换。将该定义更改为:
#define DEVID_PIIXa {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371FB_0}
会修复它。
(从评论讨论中提升到答案。)
关于C99 定义值作为文字初始化值传递给结构,失败为非常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490408/