This question already has answers here:
C fixed size array treated as variable size
(2个答案)
2个月前关闭。
我知道有一些与此错误有关的问题:
thread1,thread2,thread3,thread4,...
区别在于,我不使用变量来定义大小,而是使用宏。
这是我的工作:
如您所见,我有三个代表真实事物的宏(
这样gcc会抛出错误:
正如我们所看到的,预处理器正在做的很好。所有宏均替换为文字值。因此,数组大小中只有常数值。
我的问题
为什么gcc无法计算数组的大小?是否有强制执行计算的选项?
我使用此选项
测试:
创建一个
This answer将为您提供有关C标准规则的所有信息。
(2个答案)
2个月前关闭。
我知道有一些与此错误有关的问题:
thread1,thread2,thread3,thread4,...
区别在于,我不使用变量来定义大小,而是使用宏。
这是我的工作:
#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的浮动值。
您可以使用定点值来避免这种情况:
#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 - “在文件范围内可变修改的'variable_name'”,其大小在宏中定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59318505/