In this posting, we will take a look at the differences among #if, #ifdef, and #if defined.
#if
#if directive only works with a true or false value.
#define TEST 1
#if TEST
#error "This would be an error as well."
#endif
It can be used with an expression.
#define TEST 0
#if (TEST == 0)
#error "This would be an error as well."
#endif
It is also able to extend with #elif and #else.
#define TEST 2
#if (TEST == 1)
#error "This is an error 1."
#elif (TEST == 2)
#error "This is an error 2."
#else
#error "This is an error 3."
#endif
#ifdef
#ifdef directives checks if the name is defined.
It only checks for definition literally and values are not important. It works even it doesn't have value.
#define TEST 0
#define TEST 1
#define TEST
#ifdef TEST
#error "All three cases are treated as if thsy were defined."
#endif
If you want to handle the opposite case, use the #ifndef directive.
#ifndef TEST
#error "Error occurred because there is no definition of TEST."
#endif
#if defined
#if defined is almost the same as #ifdef except for it can handle multiple conditions.
#define TEST
#if defined (TEST) || !defined (USERNAME)
#error "This is an error."
#endif
As you can see in the above example, the opposite case can be handled by #if !defined.
And you can add multiple conditions using logical OR (||) and logical AND (&&).
You can also extend it using #elif and #else.
#define USERNAME
#if !defined (USERNAME)
#error "There is no username."
#elif !defined (USERAGE)
#error "There is no userage."
#endif
Conclusion
These directives are checked during compile-time.
So it is generally used for building multiple targets via different defined options.
I hope you can clearly understand their differences and use them appropriately.
'Embedded' 카테고리의 다른 글
[Embedded] Unittest using GoogleTest on CMake (0) | 2021.10.13 |
---|---|
[Embedded] Build using CMake (0) | 2021.10.13 |
[C] Get return address of functions (__builtin_return_address) (0) | 2021.03.02 |
댓글