Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a C preprocessor macro multiple times (through a variable)

Tags:

c

assembly

macros

I'd like to clean up my assembly code and povide a way to call "NOP" multiple times through a macro:

#define NOP() asm(" nop")

#define NOP_N( N ) \
    NOP(); \
    NOP(); \
    .... call NOP() N times

I can't figure if this is possible in a macro.

Obviously, for performance reasons, I don't want something like this:

#define NOP_N( n ) { register int i; for(i=0;i<n;i++) asm(" nop"); }

Which defeats the purpose of NOP:

L17:                                    ; NOP_N(3);
        nop
        addi      1,r0                  ; Unsigned
        cmpi      3,r0
        blo       L17

The code is in C and assembly, so no C++ can be involved in here. Also, the compiler is fairly old and doesn't support variadic macros...

like image 357
Gui13 Avatar asked Oct 18 '25 20:10

Gui13


1 Answers

I don't think a solution for unbounded N is possible. For bounded N you could do something along the following lines:

#define REPEAT_0(WHAT)
#define REPEAT_1(WHAT) WHAT REPEAT_0(WHAT)
#define REPEAT_2(WHAT) WHAT REPEAT_1(WHAT)
#define REPEAT_3(WHAT) WHAT REPEAT_2(WHAT)

#define NOP_N(N) REPEAT_##N(asm("nop");)

The first part can be autogenerated easily. The technique employed for the second part is sometimes called token pasting.

like image 162
krlmlr Avatar answered Oct 20 '25 09:10

krlmlr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!