Reputation: 49
I have a program that references an "nvml.h" file in order to execute some portion of the code. On my Linux machine, this is accomplished by including the following line in the header file:
#include "/usr/local/cuda/include/nvml.h"
However, I want the user to be able to run the program even if this file does not exist on their system. I have rendered the program modular so this can be accomplished, but I still need some method by which I can check if the file exists at all and, if not, abstain from including it in my header file.
I have tried an IF/DEF statement in order to get it working on both Windows and Linux:
#if defined(Q_OS_UNIX)
#include "usr/local/cuda/include/nvml.h"
#else
#include "C:/Users/thisUser/nvml.h"
But I cannot think of a method by which I can use the IF/DEF structure to check for file existence. Is there any way to do this with preprocessor directives in C++?
Upvotes: 0
Views: 4852
Reputation: 5257
C++17 simplifies this a bit with __has_include
which provides the ability to conditionally #include
a file only if the file is found in the system.
#if __has_include( <optional> )
# include <optional>
#elif __has_include( <experimental/optional> )
# include <experimental/optional>
#else
//
#endif
Upvotes: 3
Reputation: 238321
But I cannot think of a method by which I can use the IF/DEF structure to check for file existence. Is there any way to do this with preprocessor directives in C++?
Since C++17, there is the macro __has_include
which does exactly this.
Prior to C++17, there was no such directive in the standard, although may have been supported as an extension. A compiler may support command line argument to provide macro definitions, which can be utilised to forward the result of a check for existence prior to compilation.
That said, for your particular case, it might be better to simply include <nvml.h>
and add the parent directory to include path. See the manual of your compiler for details - or use a build system to take care of it.
Upvotes: 3
Reputation: 654
You should just do
#include "nvml.h"
set the include path while compiling depending on platform:
g++ -I/usr/local/cuda/include ...
Upvotes: 4