【问题标题】:initializer element is not constant - avr gcc初始化元素不是常数 - avr gcc
【发布时间】:2019-10-17 05:49:14
【问题描述】:

我有一个七段减速的简单代码:

#include<avr/io.h>
#include<util/delay.h>
int dp=1<<0;
int a=1<<1;
int b=1<<2;
int c=1<<3;
int d=1<<4;
int e=1<<5;
int f=1<<6;
int g=1<<7;
int ss[]={
    a|b|c|d|e|f,
    b|c,
    a|b|g|e|d,
    a|b|g|c|d,
    f|g|b|c,
    a|f|g|c|d,
    a|f|g|c|d|e,
    a|b|c,
    a|b|c|d|e|f|g,
    a|b|c|d|f|g,
    0x00
};
int main()
{
 while(1){}
}

但是当我试图从这个.c 代码生成.hex 时,这给了我错误:

这是错误:

main.c:12: error: initializer element is not constant

main.c:12: error: (near initialization for 'ss[0]')
...

所有元素都一样..

【问题讨论】:

    标签: c static initialization enumeration avr-gcc


    【解决方案1】:

    具有静态存储持续时间的变量应使用编译时常量表达式进行初始化。

    使用枚举代替变量集。例如

    #include <stdio.h>
    
    enum
    {
     dp=1<<0,
     a=1<<1,
     b=1<<2,
     c=1<<3,
     d=1<<4,
     e=1<<5,
     f=1<<6,
     g=1<<7
    };
    
    int ss[]={
        a|b|c|d|e|f,
        b|c,
        a|b|g|e|d,
        a|b|g|c|d,
        f|g|b|c,
        a|f|g|c|d,
        a|f|g|c|d|e,
        a|b|c,
        a|b|c|d|e|f|g,
        a|b|c|d|f|g,
        0x00
    };
    
    int main(void) 
    {
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      一种方法是确保它们常量(在编译时可用),方法是将其更改为:

      #define dp 0x01
      #define a  0x02
      #define b  0x04
      #define c  0x08
      #define d  0x10
      #define e  0x20
      #define f  0x40
      #define g  0x80
      

      我不会太担心将它们设置为 1&lt;&lt;n 值,因为您必须更改它的次数会非常少。


      将它们更改为 const int 似乎没有帮助。我怀疑constexpr 将是一个理想的解决方案,除了它是 C++ :-)


      如果您有可用的二进制常量,您可能还想锁定以下内容:

      static const int sevenSegMap[] = {
          // .abcdefg
           0b01111110,  // or use 0xfe if no binary constants.
           0b00110000,
           : and so on
           0b01111011,
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-04
        • 1970-01-01
        • 1970-01-01
        • 2018-01-27
        • 2015-07-21
        • 1970-01-01
        • 2016-06-28
        相关资源
        最近更新 更多