简体   繁体   中英

How to check existence of environment variables at compile time in Visual Studio 2017 C++?

I would like to check at compile-time whether an environment variable exists and I can't find a way to do it.

The reason is code maintainability: I use QT and I created an environment variable that points to the root installation directory, to be used for referencing headers and libraries. So when some years later I or a colleague of mine checks out the project and tries to compile it I want to throw a custom comprehensive error message along the lines of please install QT version XYZ and create environment variable QT_PATH to point at the root directory .

I know that a readme file is the proper way of doing it and I am creating that one as well, but I still want to know if it is generally possible to check for the existence of environment variables at compile time.

The closest I've gotten so far is using a preprocessor definition QT_INSTALLATION_PATH=$(QT_PATH); and checking it with

#if QT_INSTALLATION_PATH == '\0'
#error "..."
#endif

which throws an expression expected error if QT_PATH doesn't exist and works fine if it does exist.

The proper way to do so is to use Visual Studio generators that will do these checks for you before compilation time.

For instance, CMake does this really well and can select specific versions of Qt or OpenCV. Qt itself comes with QMake, but I suggest you aim for a common generator (not sure QMake supports OpenCV), which is CMake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM