I've started studying C++ recently, and I asked a friend who uses C++ at work on a daily basis about #ifndef and #define. He said that nobody uses because if someone writes proper code they are not neccesarry. However in the books (for beginners) I'm reading it is told to be a good practice to use them.
What if you want to use some OS specific features or want to write different code for different platforms? What if you want to be able to enable/disable certain features of your code?
Here comes the preprocessor and #ifdef
s, #define
s and #endif
s.
Suppose you want your code to work with some Windows- and Linux-specific features:
#ifdef WINDOWS
#include <something_windows_related.h>
#else
#include <posix.h>
#endif
This is often needed when working with OpenCL:
#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
If you want to switch on or off some feature when needed.
#ifdef HAVE_OPENCL
bool InitOpenCL(void) {
// some code
}
#endif
So, the answer is - these preprocessor directives are absolutely OK and sometimes are the only way to do certain things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With