关于编译器错误:C:为什么在隐式常量转换[-Woverflow]中溢出?

C: Why overflow in implicit constant conversion [-Woverflow]?

使用使用GCC 4的笨拙的Eclipse Nios II。附带的文件可以在线找到font8x8_basic.h。我曾警告过我要多次插入文件,因此我正在尝试添加关键字const和extern,只在main中包含以使其全局。
如果完成了初始化,则不应使用extern,对吗?

但是,删除const会给我警告隐式常量转换。从定义中删除const,进行清理,错误仍然存??在!!?

在font8x8_basic.h

1
2
3
4
5
#ifndef FONT8x8_H_
#define FONT8x8_H_
char font8x8_basic[128][8] = {
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},   // U+0000 (nul)
{ 0x00, 0x00, 0x0,...

在vga_util.h中

1
2
3
4
5
#ifndef VGA_UTIL_H_
#define VGA_UTIL_H_
 ....
#include"font8x8_basic.h"
...

在sensor.h

1
2
3
4
#ifndef SENSOR_H_
#define SENSOR_H_
...
#include"vga_util.h"

在main.c中

1
2
#include"vga_util.h"
#include"sensor.h"

我的构建日志如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
05:27:22 **** Incremental Build of configuration Nios II for
project     C_eng_job4 ****
make all
Info: Building ../C_eng_job4_bsp/
C:/altera_lite/16.0/nios2eds/bin/gnu/H-x86_64-mingw32/bin/make
--no-print-directory -C ../C_eng_job4_bsp/
[BSP build complete]
Info: Compiling main.c to obj/default/main.o
nios2-elf-gcc -xc -MP -MMD -c -I../C_eng_job4_bsp//HAL/inc
-    I../C_eng_job4_bsp/ -I../C_eng_job4_bsp//drivers/inc  -pipe -D__hal__
-DALT_NO_C_PLUS_PLUS -DALT_NO_INSTRUCTION_EMULATION -DALT_USE_SMALL_DRIVERS
-DSMALL_C_LIB -DALT_SINGLE_THREADED    -O0 -g -Wall -Wpedantic -Werror
-mno-hw-div -mno-hw-mul -mno-hw-mulx  -o obj/default/main.o main.c
In file included from vga_util.h:16:0,
             from main.c:31:
font8x8_basic.h:69:25: error: overflow in implicit constant conversion
[-  Werror=overflow]
 { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00},   // U+002A (*)
                     ^
 font8x8_basic.h:122:49: error: overflow in implicit constant conversion
[-Werror=overflow]
 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF},   // U+005F (_)
                                             ^
cc1.exe: all warnings being treated as errors
make: *** [obj/default/main.o] Error 1

完整的代码可以在这里看到


0xFF如果已签名,则不适合char

您应该对阵列使用unsigned char

如果这不可能,那么您可以尝试强制转换值:

1
{ ..., (char) 0xFF, ... };

然后它应该接受数字。

也可以输入负值。如果是0xFF,则为-1。可接受-128至127之间的值。

但是,如果要在任何编译器上使用它,请确保使用signed char而不是仅使用char(或者如果可以使用unsigned char),因为各种编译器都将char视为带符号(cl,您正在使用的一个)和其他未签名的(gcc)。


sensor.c包括sensor.h,后者包括font8x8_basic.h。这样就给出了数组font8x8_basic的一种定义。

main.c包含vga_util.h,其中包含font8x8_basic.h。这给出了数组font8x8_basic的另一种定义。

由于在程序中只能有一个对象的定义,因此需要在font8x8_basic.h文件中使数组为" extern"。

对于编译警告,因为您使用的是0x00到0xFF之间的初始值,请使用无符号字符。如果要将数组类型保留为char,请使用-0x80到0x7F之间的值。使用强制类型转换表示您正在强迫该值满足不建议使用的数据类型。