0

I have a macro defined like this:

`define some_macro(ARG0, ARG1 = ARG0) \
  ...

I'd like the expansion some_macro(2) to expand to some_macro(2, 2). It expands to some_macro(2, ARG0), because in the default value specification for ARG1 the text ARG0 is used and not the value of the ARG0 argument.

Is it possible to specify the default of the second argument to be the value of ARG0?

2 Answers 2

3

Here's a good summary of what you can do with SV macros.

You could mostly achieve this with two macros, like

`define M(A1) \
   `M2(A1, A1)

`define M2(A1, A2) \
   "A1 A2"

module m();

   initial begin
      $display("joined string %s", `M(bye));
      $finish;
   end
endmodule

The difference is that this would require using either M or M2 depending on the number of arguments, not just one macro for both cases.

Sign up to request clarification or add additional context in comments.

Comments

2

This can achieve the outcome you want. `ifdef ARG1 case is when a single argument is supplied, and `else is when both are. You can call another common macro there, I just wanted to demonstrate the trick to allow using the same macro name.

`define NOT_DEFINED
`define str2(ARG0, ARG1=NOT_DEFINED) \
  `ifdef ARG1 \
     `"ARG0 ARG0`" \
  `else \
     `"ARG0 ARG1`" \
  `endif

module test;

  initial begin
    $display( `str2(hello) );
    $display( `str2(hello, world) );
  end

endmodule

Output:
hello hello
hello world

6 Comments

This won't work for cases where ARG1 is not a single token, though.
Not sure what you mean. Can you give an example of where it won't work?
Actually, the code in the answer doesn't work at all.
@TudorTimi Thanks for testing. I found a syntax issue for using macros as string. It has to be `", not ", corrected in the answer now. vcs was forgiving and didn't give an error. Now it should work for all simulators.
Actually, I stand corrected, this seems to work. Let me explain what my concern was. Imagine I don't just want to pass world to ARG1, I want to pass Tudor Timi. I'd end up with code like ifdef Tudor Timi, which I thought is illegal. Somehow, and don't ask me how, this seems to work. I had the impression that what comes after ifdef is limited to only be a single token, i.e. no spaces allowed. I also tried stuff like foo#(bar) (which can come up when trying to use types as macro arguments) and that also works! Mind blown!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.