Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the C preprocessor detect if a header file cannot be found and issue a specific warning?

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?

like image 367
Robert Martin Avatar asked Feb 22 '12 20:02

Robert Martin


People also ask

What happens if header files were not used in C program?

Without a header file, you cannot run or compile your program code. In C, all program codes must include the stdio. h header file.

Is header file a preprocessor?

In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.

How do you check if a header file is included?

To check if an header file has been included or not in a C or C++ code, we need to check if the macro defined in the header file is being defined in the client code. Standard header files like math. h have their own unique macro (like _MATH_H ) which we need to check. Consider this example of checking if math.


2 Answers

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)

like image 124
Vik Avatar answered Oct 07 '22 07:10

Vik


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
like image 40
Adam Rosenfield Avatar answered Oct 07 '22 08:10

Adam Rosenfield