Basic C question (microchip xc8 compiler) regarding logic of #define

Status
Not open for further replies.

zakkos

Newbie level 6
Joined
Jan 17, 2013
Messages
12
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Visit site
Activity points
1,439
hello all, i just started learning C for pic programming and i was looking at other people's code and at the includes files provided with the compiler, especially the fundamental ones (xc.h, pic.h, pic specific headers...) and i saw this construct (it's found in pic.h)


Code C - [expand]
1
#define __delay_us(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000000.0)))



Naturally it works, but i have problems understanding the underlying logic of it.
As I understand it #define is an "alias maker", you tell the compiler to substitute the code X with Y everytime it's encountered in the program. But that's it, simple substitution. Here I see a variable, an input (x), passed to the substitute but i don't get HOW! If it was for me i would have made a function for this, and i see how useful a construct like that can be, if I find a code where a delay macro is unnecessarily made (maybe because the author didn't know about the native _delay, or because i'm porting code form another compiler) I can simply redifine the (hypothetical!) "wait(200)" to point to the native "_delay(200)". Now the question is anybody can explain to me how this construct works? X is not even declared, wouldn't it be treated as a simple character to substitute and not a value to be passed?
Would this construct be equivalent?

Code C - [expand]
1
#define wait(x) __delay_us(unsigned long x)


Thanks in advance, sorry if i made english mistakes and if i missed texts about that!
 
Last edited:

so? Will it work? Will the value of X be passed to the substitute code? how does it know to pass X and not the "i" in "unsigned" or the "a" in "wait"? just as an example to get how the compiler knows a character is just that and not a value (since X is not declared as a variable, at least in the code found in "pic.h"), this is what i don't understand...
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…