Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a macro in C

Tags:

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.

like image 541
Radoslaw Krasimirow Avatar asked Aug 24 '15 18:08

Radoslaw Krasimirow


People also ask

How do you declare a macro in C?

To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.

How do macros work in C?

Macros and its types in C/C++A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

What is macro in C with example?

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive. Here's an example. Here, when we use c in our program, it is replaced with 299792458 .

Are there macros in C?

Macro in C programming is known as the piece of code defined with the help of the #define directive. Macros in C are very useful at multiple places to replace the piece of code with a single value of the macro. Macros have multiple types and there are some predefined macros as well.


1 Answers

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)
like image 67
Snild Dolkow Avatar answered Oct 07 '22 21:10

Snild Dolkow