SystemVerilog枚举声明4位改32位消报错,咨询原因
为什么4位枚举会报错,改为32位就正常?
问题背景
将枚举类型变量从4位改为32位后编译报错消失,想明确无法保留4位枚举的原因,是否是case语句不支持小于32位的类型。
相关代码片段
测试平台(修改为32位枚举后)
module ALUtestbench; //Variable Declaration typedef enum {ADD = 32'b00, SUB = 32'b01, INV = 32'b10, RED = 32'b11} opcode_t; opcode_t opcode; //declare typed variable //Module Instance alu alu_inst( .opcode(opcode) ); initial begin opcode = opcode.first(); #10; do begin $display(opcode); $display("For opcode %s the result is: %0h", opcode.name, result); opcode = opcode.next; #10; end while (opcode != opcode.first); end endmodule
设计模块
module ALU; input reg A [4:0]; inout reg B [4:0]; output reg C [4:0]; initial begin always @ (*) begin case(opcode) ADD : C = A + B; SUB : C = A - B; INV : C = ~A; endcase end end endmodule
最初的4位枚举代码
typedef enum {ADD = 4'b00, SUB = 4'b01, INV = 4'b10, RED = 4'b11} opcode_t; opcode_t opcode; //declare typed variable
报错信息
SystemVerilog requires the width of a sized constant in this context to match the width of the enumeration type.
原因分析
枚举底层类型默认规则:SystemVerilog中,枚举类型的默认底层数据类型是
int(32位有符号整数)。当你给枚举常量指定带宽度的数值(比如4'b00)时,这个数值的宽度必须和枚举的底层类型宽度严格一致。你最初用4'b开头的4位常量,但枚举默认是32位,宽度不匹配,因此触发编译报错。并非case语句限制:case语句完全支持小于32位的类型,报错和case无关,核心是枚举常量与底层类型的宽度不匹配问题。
保留4位枚举的解决方法:如果要使用4位枚举,需要显式指定枚举的底层类型为4位宽度的类型,比如
logic [3:0],修改后的枚举定义如下:
typedef enum logic [3:0] {ADD = 4'b00, SUB = 4'b01, INV = 4'b10, RED = 4'b11} opcode_t;
这样枚举常量的4位宽度和底层类型的4位宽度一致,编译就能通过。
另外补充:你的设计模块ALU中未声明opcode端口,需要补充对应的输入声明(如果传递枚举类型,需先在模块中导入或定义该枚举类型),否则会有额外的编译错误。
内容的提问来源于stack exchange,提问作者elsa.stack
相关产品推荐
相关产品推荐

