Using #define action with externs and registers

Hi, guys! I’m new with P4 and I have lots of doubts but for now my question is how to implement (if it is possible) this code/idea:

I want to reduce my code to generate random values and set them into a register like that:

register<bit<32>>(16) register_pub_matrix;
.
.
.
#define gen_matrix(INDEX) action gen_matrix_r##INDEX##() {
        bit<32> coef;
        random(coef, 0, PARAM_Q);
        register_pub_matrix.write(##INDEX##, coef);
      }
      gen_matrix(0)
      gen_matrix(1)
      gen_matrix(2)
      gen_matrix(3)
      gen_matrix(4)
      gen_matrix(5)
      gen_matrix(6)
      gen_matrix(7)
      gen_matrix(8)
      gen_matrix(9)
      gen_matrix(10)
      gen_matrix(11)
      gen_matrix(12)
      gen_matrix(13)
      gen_matrix(14)
      gen_matrix(15)

However, I got this error message:

syntax error, unexpected IDENTIFIER, expecting ACTION or CONST or TABLE
random
^^^^^^^

If I understood correctly, I can only use a constant here, not call methods, externs, etc…
Is there any way to implement this without copy and paste multiple times the random call?

Thanks in advance!

P4 compilers typically use the C preprocessor for handling #define, and the entire definition of the macro must either (a) fit on a single line, or (b) you must put a backslash () character as the very last character of a line in order to make the definition continue with the following line. Thus if you put a backslash character at the end of your #define line, and each of the next 3 lines, but NOT the one containing ‘}’ (since you do not want to continue the macro definition after that), I suspect it might work.

In general, explicitly invoking the C preprocessor and looking at the output to see if it looks like legal P4 code is a good way to help debug such things.

1 Like

Thank you very much, Mr. Andy! It works. I still have difficulties compiling without using the scripts contained in GitHub - p4lang/tutorials: P4 language tutorials. I need to understand better how to debug the code, but thanks for the help!!