Reputation: 949
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.
Upvotes: 1
Views: 775
Reputation: 584
You could create a multiplatform library, putting the specific platform code in another specific platform library. That way, your multiplatform library can use the right specific library using #if
directives. In other words, you will isolate specific platform code.
Upvotes: 0
Reputation: 2558
the only problem I can think of is redundancy and for a serious project it's a really serious isuue. you should keep code duplication as small as possible, this is another way to do this with less code duplication:
int foo()
{
#if defined TEST
return 0;
#else
return 1;
#endif
}
int foo1()
{
#if defined TEST
return 0;
#else
return 1;
#endif
}
Upvotes: 0
Reputation: 753475
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.
Upvotes: 5