我想声明一个变量,例如
reg [7:0] foo
。
我希望 foo
根据定义值进行签名或未签名。
如果
SIGNED
为1,则签名或未签名声明。
`define SIGNED 1
reg signed [7:0] foo;
或
`define SIGNED 0
reg [7:0] foo;
我知道不可能使用
if
声明进行如下声明。
`ifdef SIGNED
if (`SIGNED==1)
reg signed [7:0] foo;
else
reg [7:0] foo;
`endif
有什么办法让它发挥作用吗?
由于宏只能有 2 个值,因此检查宏是否已定义更为常见。无需为其赋值。您只需要检查宏是否已定义并使用
`else
编译器指令而不是 else
关键字:
`ifdef SIGNED
reg signed [7:0] foo;
`else
reg [7:0] foo;
`endif
要获取
signed
版本,您只需将这一行添加到代码中:
`define SIGNED
要获取未签名的版本,请不要声明
SIGNED
宏。
请参阅 IEEE Std 1800-2017,部分:
22.6 `ifdef, `else, `elsif, `endif , `ifndef
事实上可以使用generate-
if
语句来做到这一点。您可能遇到的问题是声明必须位于 named begin/end
块内。
module top;
`ifndef SIGNED
`define SIGNED 0
`endif
if (`SIGNED ==1) begin :DECL
reg signed [7:0] foo;
end : DECL
else begin : DECL
reg [7:0] foo;
end : DECL
initial begin
DECL.foo = -1;
$display(DECL.foo);
end
endmodule
但更常见的是使用宏的定义状态在编译时在行之间进行选择。在 SystemVerilog 中,您可能需要使用
typedef
`ifdef SIGNED
typedef logic signed [7:0] byte_t;
`else
typedef logic [7:0] byte_t;
`endif
byte_t foo;