Radoslaw Krasimirow
Radoslaw Krasimirow

Reputation: 1873

How to implement a macro in C

Hi This is legal code for the compiler I use:

#use delay(clock=4M)

now I need to substitute the inside brackets text clock=4M with a macro. The digit 4 might be any digit, it should be modifiable. I tried with this

#define CLOCK_SPEED(x)        clock=xM

but didnt work.

Upvotes: 5

Views: 270

Answers (1)

Snild Dolkow
Snild Dolkow

Reputation: 6866

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

#define CLOCK(x) clock=x##M

void some_function() {
        CLOCK(4);
}

The outcome:

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

On a side note, macros like these are often the cause of hard-to-find bugs. It is usually recommended to write them like this:

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

Upvotes: 13

Related Questions