How to implement a macro in C

Hey. This is legal code for the compiler used:

#use delay(clock=4M) 

Now I need to substitute the text inside the brackets clock=4M macro. Digit 4 can be any digit, it must be modifiable. I tried with this

 #define CLOCK_SPEED(x) clock=xM 

but does not work.

+5
source share
1 answer

What you want is a preprocessor concatenation operator , ## .

 #define CLOCK(x) clock=x##M void some_function() { CLOCK(4); } 

Result:

 tmp$ cpp -P test.c void some_function() { clock=4M; } 

On the side of the note, macros like these often cause hard-to-reach errors. it is generally recommended to write them as follows:

 #define CLOCK(x) do { clock=x##M; } while(0) 
+13
source

All Articles