gpt4 book ai didi

c - "Initializer element is not constant"- 但显然是

转载 作者:行者123 更新时间:2023-12-02 01:42:34 25 4
gpt4 key购买 nike

我知道这条消息的意思,但不知道为什么会这样。

main.c:26:2: error: initializer element is not constant
rgb24_xrgb(0xB14835), // brick red

我的代码:

typedef uint32_t rgb24_t;

// Color structure
typedef struct {
uint8_t r;
uint8_t g;
uint8_t b;
} xrgb_t;

// Table of colors
const xrgb_t COLORS[] = {
rgb24_xrgb(0xB14835), // brick red
rgb24_xrgb(0x4C1661), // indigo
rgb24_xrgb(0xA3268E), // royal purple
};

这是我的宏:

#define xrgb(rr, gg, bb) ((xrgb_t) { .r = ((uint8_t)(rr)), .g = ((uint8_t)(gg)), .b = ((uint8_t)(bb)) })
#define rgb24_r(c) ((((rgb24_t) (c)) >> 16) & 0xFF)
#define rgb24_g(c) ((((rgb24_t) (c)) >> 8) & 0xFF)
#define rgb24_b(c) ((((rgb24_t) (c)) >> 0) & 0xFF)
#define rgb24_xrgb(c) xrgb(rgb24_r(c), rgb24_g(c), rgb24_b(c))

预处理器输出在这里:

const xrgb_t COLORS[] = {
((xrgb_t) { .r = ((uint8_t)(((((rgb24_t) (0xB14835)) >> 16) & 0xFF))), .g = ((uint8_t)(((((rgb24_t) (0xB14835)) >> 8) & 0xFF))), .b = ((uint8_t)(((((rgb24_t) (0xB14835)) >> 0) & 0xFF))) }),
((xrgb_t) { .r = ((uint8_t)(((((rgb24_t) (0x4C1661)) >> 16) & 0xFF))), .g = ((uint8_t)(((((rgb24_t) (0x4C1661)) >> 8) & 0xFF))), .b = ((uint8_t)(((((rgb24_t) (0x4C1661)) >> 0) & 0xFF))) }),
((xrgb_t) { .r = ((uint8_t)(((((rgb24_t) (0xA3268E)) >> 16) & 0xFF))), .g = ((uint8_t)(((((rgb24_t) (0xA3268E)) >> 8) & 0xFF))), .b = ((uint8_t)(((((rgb24_t) (0xA3268E)) >> 0) & 0xFF))) })
};

在我看来相当稳定。

问题出在哪里?

最佳答案

来自 C11 6.7.9/4(C99 有类似的文本):

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

来自 C11 6.6“常量表达式”:

More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:

  • an arithmetic constant expression,
  • a null pointer constant,
  • an address constant, or
  • an address constant for a complete object type plus or minus an integer constant expression.

复合文字不是那些要点,因此在初始化程序中是不允许的。

如果复合文字的初始值设定项都是满足这些条件的常量表达式,我看不到任何关于为什么不允许这样做的理由。

不过,您可以通过使用不带复合字面量的初始值设定项来解决这个问题:

const xrgb_t COLORS[] = {
{ .r = ........... , .g = ............., .b = ........ },
{ .r = ....... // etc.
};

这应该很容易在您现有的代码中完成,方法是重命名您的宏以仅提供 { } 部分,然后使用另一个具有 (const xrgb_t) 原始名称的宏rgb24_xrgb(X) 使复合文字或其他。

注意。使复合文字 const 允许编译器将其存储在只读区域中。

关于c - "Initializer element is not constant"- 但显然是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27629432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com