Make a custom error in C if header file not found

89 Views Asked by At

Is there a way to make C code show a custom error if a header file is not found? I feel this would particuraly useful for trying to compile windows code on linux. For example, instead of "Windows.h not found". the error would be "This code can only compile on windows".

2

There are 2 best solutions below

0
David Ranieri On BEST ANSWER

You can check the OS and use the preprocessor directive #error if it doesn't match:

#ifdef _WIN32
#include <windows.h>
#else
#error "This code can only compile on windows"
#endif

Or if you prefer, in a Makefile:

ifneq ($(OS),Windows_NT) 
$(error This code can only compile on windows)
endif
0
Weijun Zhou On

To directly address the question in title, in C23 you can detect the validity of a include by __has_include. It is also available as an extension in various compilers (including GCC and Clang) before C23. This question asks about making it available for pre-C23 MSVC but has no answer yet.

You can use it like,

#if __has_include(<windows.h>)
#include <windows.h>
#else
#error "This code can only compile on windows."
#endif