首页 > 解决方案 > 错误“表达式必须具有恒定值”

问题描述

当我使用 const 变量“a”和“b”来初始化结构化变量“cfg”时,我面临以下编译器问题“表达式必须具有常量值”

static const unsigned int a = 1;
static const unsigned int b = 2;


typedef struct
{
    const uint32 InitTypestruct_elem1;   
    const uint32 InitTypestruct_elem2;   
}InitType;

typedef struct
{
    InitType BoardTypestruct_elem1;
}BoardType;


static const BoardType cfg =
{
    /* pbgc cfg */
    .BoardTypestruct_elem1 =
    {
        ***.InitTypestruct_elem1 = a,
        ***.InitTypestruct_elem2 = b
    }
};


const InitType *cfg(void)
{
    return &cfg.BoardTypestruct_elem1;
}


int main()
{
    //cfg

    return 0;
}

编译器警告导致与 *** 一致

为什么会发生这个问题?a 和 b 是常量值吗?

标签: c

解决方案


简化其他答案:

static const unsigned int a = 1;

a是一个变量,不管它是 const。您不能在编译时用另一个(全局)变量初始化全局变量。编译器不会将其视为常量。


推荐阅读