Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using #ifndef and #define in C++ obsolete?

Tags:

c++

include

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.

like image 846
user137425 Avatar asked Mar 28 '16 11:03

user137425


1 Answers

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 #ifdefs, #defines and #endifs.

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.

like image 168
ForceBru Avatar answered Nov 13 '22 14:11

ForceBru