0
\$\begingroup\$

I would like to create a task for debug purposes in which I can print the name of the variable and assign the value to that variable. I can think of these ways to do it with the following pseudo-code:

1) pass the variable by reference and the value, which seems to work fine and the variable gets assigned, but I can not figure out how to print its name.

reg myVarName;  
debug_message1(myVarName, 1'b1);

// assigns myVarName=1'b1;
// Expected print output: "The variable name is myVarName and its value is 1"
task debug_message1(ref reg var, reg val);

  var = val;
  print("The variable name is %s and its value is %d", var.name, var);
endtask

2) pass variable name as a string, which makes it easy to print, but I don't know how to convert the string that contains the name of the variable to the actual variable, so I could assign to it.

reg myVarName;
debug_message2("myVarName", 1'b1);

// Need to somehow assign myVarName=1'b1;
// Printed output: "The variable name is myVarName and its value is 1"
task debug_message2;
  input string var;
  input    reg val;

  `var` = val; // need to make assignment here 
  print("The variable name is %s and its value is %d", var, val);
endtask

3) Pass the variable, its name as a string, and the value, which does not like the second and the third arguments, because they are defined when calling the task, which gives the following error message:

Illegal connection to the ref port 'varname' of function/task 'debug_message3',formal argument should have same type as actual argument.

The same kind of error comes up for the 'val' argument.

reg myVarName;
debug_message3(myVarName, "myVarName", 1'b1);

// Assign myVarName=1'b1;
// Printed output: "The variable name is myVarName and its value is 1"
task debug_message3(ref reg var, string varname, reg val);

  var = val; // need to make assignment here 
  print("The variable name is %s and its value is %d", varname, var);
endtask

Is there a way to implement any of the 1, 2 or 3 approaches?

\$\endgroup\$
1
\$\begingroup\$

You can make a macro to do this instead of a task

`define debug_message(Var,Value) \
begin \
  Var = Value; \
  $display("The variable name is %s and its value is %d", `"Var`", Var); \
end

A macro treats its arguments as just text, giving you the ability to reinterpret them as identifiers or strings. The `" instead of " is what lets lets you have macro arguments inside a string.

\$\endgroup\$
2
  • \$\begingroup\$ Dave, this is exactly what I needed. How do I fix the following: define set_arg(var) begin if ($value$plusargs("var=%d", var)) $display("%d => %s", var, "var"); end \$\endgroup\$
    – Nazar
    May 8 '20 at 15:42
  • \$\begingroup\$ See edited answer. \$\endgroup\$
    – dave_59
    May 8 '20 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.