How do I wrap $display so it only prints if DEBUG is defined?

In pseudo-Verilog/Python, here’s what I’d like to do:

`define DEBUG

task debug_print(*args);
  `ifdef DEBUG
    $display(*args);
  `endif
endtask

initial
  int x = 3;
  debug_print("X is %0d", x); // only prints if DEBUG is defined
end

This avoids having to add the ifdef-endif pair to every debug print statement. The obvious problem is that even though $display() can take a variable number of arguments, I don’t know of a way for user-defined tasks to accomplish that, so I’m not sure how I’d be able to wrap $display().

Is there a way for user-defined tasks to accept a variable number of parameters? If not, how do you accomplish debug prints without putting each statement within an if or ifdef clause?

>Solution :

The standard way to do this is to construct a string and pass that to your debug task:

`define DEBUG

module tb;

task debug_print(string str);
    `ifdef DEBUG
        $display(str);
    `endif
endtask

initial begin
    int x = 3;
    debug_print($sformatf("X is %0d", x)); // only prints if DEBUG is defined
end

endmodule

A common practice is to use $sformatf to build up the string you want to display. This is similar to the UVM `uvm_info macro.

Leave a Reply