C Using #define to specify or function alias

I'm a bit confused if I can use #define to point to a function. I have a codec / DSP that automatically creates code pages as follows:

SIGMA_WRITE_REGISTER(address, data, length); SIGMA_WRITE_REGISTER(address, data, length); SIGMA_WRITE_REGISTER(address, data, length); .... 

Then in another .h file they do this:

  #define SIGMA_WRITE_REGISTER( address, data, length ) { /*TODO: implement macro or define as function*/} 

That nothing helps in writing registers. This is great, although I wrote code for my microuser to write registers in I2C, and it seems to work. Now I don’t want to just paste this code into the above definition and instantiate it 1000 times. I was hoping I could just use the definition as an alias for my function?

Sort of:

 #define SIGMA_WRITE_REGISTER(address, data, length) { my_i2_c_func(address, data, length)} 

I tried something like this and it compiled, but I'm not sure if it works. Is this the right thing, or am I barking the wrong tree?

+5
source share
3 answers

Yes, you can use #define to indicate a full function or alias.

Consider a simpler example below, just for understanding.

 #define STRLEN(x) my_strlen(x) 

and

 int my_strlen(char *p) { // check for NULL pointer argument? int x; for (x = 0; *p++; x++); return x; } 

Now, in your code, you can use STRLEN as you wish.

Note. As for the presence of { } , you can either get rid of them, or use the do..while , or define the function as part of the macro itself. Your choice. However, as MACRO expands during the preprocessing phase [resemble text replacement], you need to be careful about using {} and ; . Using MACRO should not violate the code.

+4
source

It is (almost) valid, but you need a semicolon after the last closing bracket and before the closing bracket.

The brackets in the replacement are completely redundant, so you delete them anyway, and then you do not need to add a semicolon. The brackets give you a null statement after each block of statements (and if you save a semicolon in a macro, you also get a null statement after every macro call.

The comments in the .h file indicate that you can replace the macro with a function (call). What you do is mostly beautiful.

+2
source
 #define SIGMA_WRITE_REGISTER my_i2_c_func 
0
source

Source: https://habr.com/ru/post/1209795/


All Articles