10

I have a C file that needs a specific header file. If that header file does not exist, I want the preprocessor to issue a specific warning. Something like:

#if !(#include <special.h>)
#warning "Don't worry, you can fix this."
#warning "You just need to update this other repo over here:"
#endif

Is this possible with the C preprocessor?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Robert Martin
  • 16,759
  • 15
  • 61
  • 87

4 Answers4

20

I know this is a old question, but I also needed a way to do this and I was disappointed when I read these answers. It turns out that clang has a nice __has_include("header name") directive that works flawlessly to do what you need :) Maybe you want to check if the directive is available first by calling #if defined(__has_include)

Vik
  • 1,897
  • 12
  • 18
9

No, this is not possible. All you can do is try to #include the header, and if it doesn't exist, the compiler will give you an error.

An alternative would be to use a tool like GNU autoconf. autoconf generates a shell script called configure which analyzes your build system and determines things like whether or not you have certain header files installed, and it generates a header file consisting of macros indicating that information.

For example, it might define HAVE_SYS_TIME_H if your build system includes the header <sys/time.h>, so you can then write code such as:

#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#warning "Don't worry, you can fix this."
#endif
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
8

You could always check if the #define X macro, from the included file, is ... defined :)

Chad
  • 111
  • 1
  • 12
IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
  • 1
    @asaelr Not sure if this is true for everyone, but in my build setup the PP/CC will bravely press on if it can't find an include file. So `#include ` followed by `#ifndef __SPECIAL_H__` works for me – Robert Martin Feb 22 '12 at 21:15
  • If I have cross-platform code, I want to see if `platform-specific.h` exists before I import it. Using this approach with clang, I have to import it to see if something is defined, but if it doesn't exist, attempting to import it is a compiler/linker error – Ky - Jun 11 '20 at 16:49
  • This won't work in all compilers because they'll fail the compile on the missing include. – Azeroth2b Jan 11 '21 at 15:36
-5

If all you need is a warning that the header file is not there (and no custom code), then most compilers will already give you one.

$ LC_MESSAGES=en_US gcc -c bar.c
bar.c:1:17: fatal error: foo.h: No such file or directory
compilation terminated.
jørgensen
  • 10,149
  • 2
  • 20
  • 27