Search code examples
cconditional-compilation

Usage of #if defined for function definition


I need to know if the usage of #if defined is correct and know the possible cons of using it this way.

#if defined TEST
int foo()
{
   return 0;
}
int foo1()
{
   return 0;
}
#else
int foo()
{
   return 1;
}
int foo1()
{
   return 1;
}
#endif

EDIT: I am trying to use this code for two different platforms I am working on.


Solution

  • It is syntactically correct.

    The primary disadvantage of that way of organizing it is that you repeat the definitions of the functions for both the test and non-test cases. What is not possible to tell from a carefully minimized example is how much of a problem that will be. The other way to organize it, assuming that the current return statements are surrogates for a more substantial block of code (at least in one of the two cases) would be:

    int foo(void)
    {
    #if defined TEST
       return 0;
    #else
       return 1;
    #endif /* TEST */
    }
    
    int foo1(void)
    {
    #if defined TEST
       return 0;
    #else
       return 1;
    #endif /* TEST */
    }
    

    For these exact functions, you could do:

    #ifdef TEST
    #define RETVAL 0
    #else
    #define RETVAL 1
    #endif /* TEST */
    
    int foo(void)
    {
       return RETVAL;
    }
    int foo1(void)
    {
       return RETVAL;
    }
    

    However, your real functions are unlikely to be quite so simple, so this doesn't translate well.

    The general goal is to avoid repetition, and to avoid conditional compilation showing in your functions.