Verilog 中未声明的标识符

Undeclared identifier in Verliog

我正在用 Verilog 做一些项目,这部分代码遇到了一些问题。

'''
parameter OP_mode = 2'b01;

if(OP_mode == 2'b00)
  parameter k=4;
else if(OP_mode == 2'b01)
  parameter k=8;
      .
      .
      .
reg [k-1:0] inputs;

'''

在这种情况下,编译器给我错误“Undeclared Identifier: k” 我该如何解决这个错误?

您在无法从外部引用的未命名代码块内声明参数 (IEEE 1800-2017 SystemVerilog LRM)

27.5 Conditional generate constructs

Generate blocks in conditional generate constructs can be named or unnamed, and they may consist of only one item, which need not be surrounded by begin-end keywords. Even if the begin-end keywords are absent, it is still a generate block, which, like all generate blocks, comprises a separate scope and a new level of hierarchy when it is instantiated.

parameter OP_mode = 2'b01;
if(OP_mode == 2'b00) begin: block
  parameter k=4;
end
else if(OP_mode == 2'b01) begin : block
  parameter k=8;
end
logic [k-1:0] inputs;

更好的方法是使用函数调用:

module top;
  
  parameter OP_mode = 2'b01;
  
  function int f_k;
    if(OP_mode == 2'b00)
       return 4;
    else if(OP_mode == 2'b01) 
       return 8;
    return 0;
  endfunction
  
  parameter k = f_k();
  logic [k-1:0] inputs;