views:

127

answers:

4

I need to figure out the operating system my program is running on during runtime.

I'm using Qt 4.6.2, MinGW and Eclipse with CDT. My program shall run a command-line QProcess on Windows or Linux. Now I need a kind of switch to run the different code depending on the operating system.

Thx

+3  A: 

Do it at compile time using #ifdef.

Under windows, WIN32 is defined.

So, do:

#ifdef WIN32
// Windows code here
#else
// UNIX code here
#endif
houbysoft
+1  A: 

This is typically done using precompiler directives to control what chunk of code is included/excluded from your build.

#ifdef WIN32
  // ...
#endif

This results in (arguably) uglier code, but targeted binaries.

Alex
+9  A: 

In Qt the following OS macros are defined for compile time options

Qt/X11 = Q_WS_X11 is defined.
Qt/Windows = Q_WS_WIN is defined.
Qt/Mac OS X = Q_WS_MACX is defined

Then the QSysInfo class gives you the OS version and other options at runtime.

Martin Beckett
QT-specific macros. Me like. +1
Randolpho
Ok, but then I have to deliver different version depending on the operating system?
walle
@walle: yes, definitely. This is not a bad thing.
Randolpho
you should anyway compile for each target, so there's no problem at all.
ShinTakezou
@walle - yes, without some sort of runtime system like python/java/c# the executable format is different on each OS. Qt just lets you write the same source file for each.You also generally need different installers on each platform
Martin Beckett
@Martin: atm my program is small enough to be just one file on windows. But there is a possibility that it shall run on linux one time ...@Randolpho: There is also a Q_OS_WIN32 macro with the appropriate Q_OS_LINUX macro, so I will try this combination.
walle
@walle - even with Qt an executable (without some serious trickery) can't run on both. Windows wouldn't recognise a Linux executable or know what to do with it.
Martin Beckett
@Martin: this is one thing i knew before ;) it was just a comment on the different installers you mentioned ...
walle
+4  A: 

Qt offers QSysInfo if you really need to get at this at run-time. Useful for appending to a crash report but for anything else try to do it at compile time.

Troubadour