PDA

View Full Version : Detect which OS?



December
20th May 2007, 13:11
How can my program find out which Operating System it is running on?

I have an app that compiles on Linux, Windows and OSX, but obviously it needs to some things differently on each (like the location is saves its settings for example).

Thanks in advance.

wysota
20th May 2007, 13:17
Take a look at Q_OS_* macros.

December
20th May 2007, 13:31
That looks hopeful, but how do I use a pre-processor directive in normal C++ code (and not in the header).. sorry if that's a bit of a noob question, never needed to do that before.

wysota
20th May 2007, 13:51
void myCustomFunc(){
#ifdef Q_OS_LINUX
linuxNativeCode()
#endif
//...
#ifdef Q_OS_WIN32
winApiCalls()
#endif
}

December
20th May 2007, 13:57
Wow, that was easy, exactly what I needed.

Thanks loads for the help.

Michiel
20th May 2007, 14:01
Qt has a lot of this already done. For application settings, for example, you can use the QSettings class.

hvengel
24th May 2007, 23:01
To add to that there are many that consider using conditional compilation to be "evil". So you should avoid this if at all possible. In particular Qt has a number of things that hide differences like this in high level libraries. QSettings is an example. So using QSettings Qt will take care of using the registry on Windows, Carbon on Mac and will use a text file on Linux/Unix... for user setting and your code for all of these platforms will be the same or very nearly the same.

So if you find yourself thinking that you will need to use conditional compilation to handle something ask here first and in most cases someone will be able to tell you which Qt objects to use so that you can avoid this. In the end your code will be simpler and easier to understand and maintain. This is not always possible but you should only have to use conditionals under a very limited number of cases and most of those will involve things that are at a very low level (typically hardware level stuff).