【问题标题】:Defining static const value form a struct从结构中定义静态常量值
【发布时间】:2023-03-12 11:02:01
【问题描述】:

我在 Keil 中使用 C99 对微处理器进行编程,但在使用结构定义静态常量时遇到了困难。 以下编译没有问题:

static uint8_t const addr1 = 0x76;
static uint8_t const addr = addr1;

但以下不是:

typedef struct
{
    uint8_t const           address;    
} bmp280_t;

static bmp280_t bmp280_0 = {
        .address    =   0x76,
    };

static uint8_t const addr2 = bmp280_0.address;

最后一行导致编译错误:

......\main.c(97): error: #28: expression must have a constant value static uint8_t const addr2 = bmp280_0.address;

我尝试在 Visual Studio 中进行复制,但两种情况都无法编译。我不知道这是因为它是编译为 cpp 还是使用不同的标准..

【问题讨论】:

  • 如果第一个编译得很好,那么它使用了编译器扩展。常量变量不能用于标准 C 中的初始化。
  • 好吧,我想可能是这样的。谢谢。

标签: c struct static constants


【解决方案1】:

您使用的初始化程序(即:bmp280_0.address)不是编译时常量。但是,您可以执行以下操作:

#define ADDRESS 0x76   

typedef struct
{
    uint8_t const           address;    
} bmp280_t;

static bmp280_t bmp280_0 = {
        .address    =   ADDRESS,
    };

static uint8_t const addr2 = ADDRESS;

也就是说,定义一个预处理器宏ADDRESS,它会在被预处理器替换时产生编译时常量0x76,并使用这个预处理器宏作为初始化器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多