简体   繁体   中英

How to bring an environment variable into build to use in #ifdef

Is it possible to have an OS environment variable define a macro for use in C++ code in VS2013?

For example, I would like to possibly have the environment variable DEV_LOG_DIRECTORY set, and perform the following in my C++ source file:

#ifdef DEV_LOG_DIRECTORY
    logging::set_dir(DEV_LOG_DIRECTORY)
#endif

I would like to keep the actual value, and whether the macro is defined or not, out of the Visual Studio project file, so that different developers can set this how they feel and not be affected by other developer's preference. Everything I've found says to specify this in the project options, but that won't work in this case.

If there is a better way to accomplish my goal, I'm open to alternatives!

Are you sure you want to do this at compile-time ? Even if it were possible (and I do not know if it is), the environment variable would only exist on the developer's machine, and would only be processed when compiling on that machine. Once you move the compiled executable to another machine, the set_dir() value would have been hard-coded into the app, but the actual target folder would likely not exist on the current machine. You probably want to instead read the environment variable from the OS that your app is actually running on, and then use it if defined, eg:

char LogDir[32767] = {0};
if (GetEnvironmentVariableA("LOG_DIRECTORY", LogDir, _countof(LogDir)) > 0)
{
    logging::set_dir(LogDir);
}
else if (GetLastError() != ERROR_ENVVAR_NOT_FOUND)
{
    // error reading the environment variable...
}

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