Reputation: 1891
I have a library project with a inline function in my Lib.h
:
static inline void DoStuff(void) __attribute__ ((always_inline));
static inline void DoStuff(void)
{
#if(SYMBOL == 1)
// Stuff
#elif(SYMBOL == 2)
// Other stuff
#endif
}
I compile my library into libLib.a
and set SYMBOL=2
. Now I use this library and the header Lib.h
in some other project. This project set SYMBOL=1
and calls DoStuff()
in this project. Which part of the #if
directive gets executed? I assume that the compiler will run the part with #if(SYMBOL == 1)
but I´m not sure. How does the compiler handle it?
Upvotes: 2
Views: 65
Reputation: 18420
First of all, the correct syntax for the preprocessor directives is:
static inline void DoStuff(void) __attribute__ ((always_inline));
static inline void DoStuff(void)
{
#if SYMBOL == 1
// Stuff
#elif SYMBOL == 2
// Other stuff
#endif
}
You can also leave the parentheses around the comparison if you prefer, but it isn't strictly necessary as with the regular if
condition.
If you are not sure, which code parts are active, you can use #warning
to make it obvious:
#if SYMBOL == 1
#warning Symbol == 1
// Stuff
#elif SYMBOL == 2
#warning Symbol == 2
// Other stuff
#endif
Upvotes: 3
Reputation: 768
In C, lines which starts with # are pre-processed by the preprocessor, which means that when you compile this, the compiler will read it like this (for example, if in the library SYMBOL=1:
static inline void DoStuff(void) __attribute__ ((always_inline));
static inline void DoStuff(void)
{
//only the stuff that were in the block of SYMBOL=1
}
When you compile the code into a library, it no longer knows SYMBOL. When you change SYMBOL in your code, it will only change it for this project. To resolve this issue, use the macros in a header:
In DoStuff.h:
void __do_stuff1();
void __do_stuff2();
static inline void DoStuff()
{
#if SYMBOL==1
__do_stuff1();
#elif SYMBOL==2
__do_stuff2();
#endif
}
In DoStuff.c:
void__do_stuff1(){...}
void __do_stuff2(){...}
Upvotes: 0