Using #define to check operating system
Hi again, got a new one here. Kind of surprised I've never hit up against this before.
I'd like to be able to specify a #define for the OS used in the build. That way, in various included header files, I can specify different versions of functions which contain OS-dependent code. Here's a non-working example of what I'd like the code to look like, though I suspect that this kind of thing is impossible using #if checks, even if I were to cloak them in macros. Is there another way?
Code:
//This is what I would like the code to resemble.
#include <iostream>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
int OS_Table(const string& str)
{
if(str == "windows")
return 0;
else if(str == "mac")
return 1;
else if(str == "*nix")
return 2;
}
#define OS_BUILD OS_Table("windows")
#if OS_BUILD == OS_Table("windows")
void Function() { cout << "Windows" << endl; }
#elif OS_BUILD == OS_Table("mac")
void Function() { cout << "Mac" << endl; }
#elif OS_BUILD == OS_Table("*nix")
void Function() { cout << "*nix variant" << endl; }
#else
void Function() { cerr << "Invalid operating system." << endl; }
#endif
int main()
{
Function();
return 0;
}
Re: Using #define to check operating system
You have to determine the OS based on preprocessor symbols defined by the compiler. If you're primarily worried about just windows, mac and linux, you can usually do something like:
Code:
#define PLATFORM_WIN32 1
#define PLATFORM_APPLE 2
#define PLATFORM_LINUX 3
#if defined(__WIN32__) || defined(_WIN32)
#define PLATFORM PLATFORM_WIN32
#elif defined(__APPLE_CC__)
#define PLATFORM PLATFORM_APPLE
#else
#define PLATFORM PLATFORM_LINUX
#endif
Which you'd then use like so:
Code:
std::string platformName()
{
#if PLATFORM == PLATFORM_WIN32
return "Win32";
#elif PLATFORM == PLATFORM_APPLE
return "Mac";
#else
return "Linux";
#endif
}
Re: Using #define to check operating system
Os_table only returns something at run-time, but (#if condition) requires a condition at compile time!
Code:
#ifdef MY_WINDOWS_DEF
void Function() { cout << "Windows" << endl; }
#elif defined(MY_MAC_DEF)
void Function() { cout << "Mac" << endl; }
#elif defined(MY_NIX_DEF)
void Function() { cout << "*nix variant" << endl; }
#else
void Function() { cerr << "Invalid operating system." << endl; }
#endif
where one of MY_WINDOWS_DEF, MY_MAC_DEF and MY_NIX_DEF needs to be #defined.