What is the purpose of HAVE_* macros?

Viewed 626

I am reusing some C/C++ source files part of an autotools project within a CMake project and I see many source files littered with lines like:

#ifdef HAVE_UNISTD_H
#include <unistd.h>  // for getpid()
#endif

I would understand the purpose of this construct if getpid() was optional and its call was surrounded by equivalent HAVE_UNISTD_H directives. However, without HAVE_UNISTD_H the source file does not compile, complaining that getpid() is not defined. This feels a lot more cryptic than the compiler letting me know that unistd.h was not found.

Of course, this is only an example. Other popular macros include HAVE_STDINT_H, HAVE_INTTYPES_H, etc. whose presence is mandatory to compile the source file.

Why are HAVE_* guards included at all? I feel they only bring disadvantages:

  • Reusing such source files requires making sure the right header files are present and the right HAVE_* macros are defined.
  • In case of a mistake, the developer gets a more cryptic message, i.e., the compiler does not report the root cause (header not found) but an ancillary error (type/function not found).
  • The source files are a bit longer and a bit more tedious to read, i.e., #includes mixed with #ifdefs.
2 Answers
Related