我知道有一些与此错误相关的问题:
C fixed size array treated as variable size,thread1,thread2,thread3,...
不同的是,我不使用变量来定义大小,而是使用宏。
这就是我所做的:
#define SIZE_A 250 // Real world value
#define SIZE_B 80 // Real world value
#define SCALE 0.25 // Real world value
#define TOTAL_A (uint16_t)(SIZE_A/SCALE)
#define TOTAL_B (uint16_t)(SIZE_B/SCALE)
#define TOTAL TOTAL_A*TOTAL_B
#define SIZE_1 (uint16_t)(TOTAL*0.3)
#define SIZE_2 4000
typedef struct {
toto_t toto[TOTAL_A][TOTAL_B];
foo_t foo[SIZE_1][SIZE_2];
} bar_t;
如您所见,我有三个代表真实事物的宏( SIZE_A
、 SIZE_B
、 SCALE
)。根据这些,我定义了二维数组 ( TOTAL_A
) 的大小 ( TOTAL_B
、 toto_t toto
) 以及该数组 ( TOTAL
) 中的单元格总数。然后,我取出该总数的一部分 ( SIZE_1
) 来定义我要创建的其他数组 ( foo_t foo
) 的大小。
这样 gcc 就会抛出错误: Variably modified 'foo' at file scope
。因此,我查看了预处理器输出:
typedef struct {
toto_t toto[(uint16_t)(250/0.25)][(uint16_t)(80/0.25)];
foo_t foo[(uint16_t)((uint16_t)(250/0.25)*(uint16_t)(80/0.25)*0.3)][4000];
} bar_t;
正如我们所看到的,预处理器做得很好。所有宏都被替换为文字值。因此数组大小中只有常量值。
我的问题
为什么 gcc 无法计算数组的大小?是否有一个选项可以强制它进行计算?
我使用此选项 -O3 -Wall -Wextra -Werror
进行编译。
测试:
创建一个test.h
并放入我发布的代码并在开头添加typedef uint16_t toto_t; typedef uint16_t foo_t;
。并创建一个 test.c
文件:
#include <stdio.h>
#include <inttypes.h>
#include "test.h"
int main() {
printf("hello world\n");
return 0;
}
最佳答案
这里的问题是 SCALE 的 float 值。
您可以使用定点值来避免它:
#define SIZE_A 250 // Real world value
#define SIZE_B 80 // Real world value
#define SCALE 25 // Real world value
#define TOTAL_A (SIZE_A*100/SCALE)
#define TOTAL_B (SIZE_B*100/SCALE)
#define TOTAL TOTAL_A*TOTAL_B
#define SIZE_1 (TOTAL*3/10)
#define SIZE_2 4000
typedef struct {
toto_t toto[TOTAL_A][TOTAL_B];
foo_t foo[SIZE_1][SIZE_2];
} bar_t;
This answer将为您提供有关 C 标准规则的所有信息。
关于c - "Variably modified ' 变量名 ' at file scope"大小在宏中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59318505/