Reputation: 129
I wanna call another function from a function with macros involved.
Here's a sample:
#if RAND
int functionA() {
//How to call the bottom function from here?
}
#else
int functionA() {
}
Notice they are both the same function names. How do I call the 'else' function from the 'if' function.
Thanks
Upvotes: 0
Views: 7010
Reputation: 9375
About as close as you'll get is one of the following:
int functionA()
{
#if RAND
/* stuff that happens only when RAND is defined */
#endif
/* stuff that happens whether RAND is defined or not */
}
Or maybe this:
#if RAND
#define FUNCA() functionA_priv()
#else
#define FUNCA() functionA()
#endif
int FUNCA()
{
/* the non-RAND version of functionA().
* It's called functionA_priv() when RAND is defined, or
* functionA() if it isn't */
}
#if RAND
int functionA()
{
/* The RAND version of functionA(). Only defined if RAND
* is defined, and calls the other version of functionA()
* using the name functionA_priv() via the FUNCA() macro */
FUNCA();
}
#endif
The use of the FUNCA()
macro in the second version allows the normal version of functionA()
to call itself recursively using the FUNCA()
macro instead of functionA()
if necessary, since FUNCA()
will provide the right identifier regardless of which name is used for the function.
Upvotes: 1
Reputation: 477030
That makes no sense and isn't possible. Macros are dealt with by the preprocessor, so the compiler doesn't even end up seeing the code for the disabled function at all!
Avoid macros if you can. They cheat you out of getting the benefits of a clever compiler. Write your code in C as much as you can, and not in search-and-replace trickery.
For example, you could make a function int functionA(int type)
and implement different parts conditionally on type
...
Upvotes: 3
Reputation: 410652
You don't. Preprocessor macros are evaluated when the program is compiled. In this case, only one of the functions will be compiled, based on the value of RAND
at compile time. It seems like maybe you want to use an if statement here, rather than a preprocessor macro.
Upvotes: 0
Reputation: 3951
You cannot. Only one of the functions will be created by the compiler, depending on the value of the RAND
.
Upvotes: 2
Reputation: 37950
I can't see how that can be done directly. Instead, create a separate function outside of the #if/#else
, say, functionB()
, and move all the code from the last functionA()
there and replace it by a call to functionB()
. Then, you can call functionB()
from the first functionA()
.
Upvotes: 1