How can I detect if the operating system is Windows in C++/C?
Asked
Active
Viewed 2.4k times
9
-
How are you compiling code that is binary compatible with multiple operating systems? – Cody Gray - on strike Dec 06 '10 at 05:39
-
Are you asking about compilation time, or runtime? – wkl Dec 06 '10 at 05:40
-
runtime, when the program runs – Daniel Dec 06 '10 at 05:41
-
1You should not have to do that at all, considering you will have to build code that runs on Windows, and that is incompatible with binaries you'd build for Linux, or Mac, or FreeBSD, etc. Reading your other comments, what you really want is compile time determination to build code specifically for Windows. – wkl Dec 06 '10 at 05:42
-
When you compile a program down to "native code" (CPU-specific machine code) you must normally target a specific operating system (and often version thereof) that the resultant executable will be able to run on. This is different from interpreted languages like Ruby or Java where a native-code program exists to read the source code or a representation thereof ("byte code") that represents the program. Still, it is possible for you to compile a Windows program and run it under a Windows emulator, such as Linux's WINE, is that what you want to be able to recognise? – Tony Delroy Dec 06 '10 at 05:45
-
You cannot do this at runtime, because the process of compiling creates code for a specific platform. It simply won't run on other platforms; you have to recompile for them. Therefore, your Windows program is **always** running on Windows, because otherwise it isn't running at all. – Karl Knechtel Dec 06 '10 at 05:56
3 Answers
38
#ifdef _WIN32
cout << "This is Windows." << endl;
#endif
This will allow you define blocks for windows only. As long as the preprocessor macro is defined.
This is a compile time thing, not a runtime thing.

Paul
- 2,729
- 20
- 26
-
3Will this work for windows 64 bits? I can test ofcourse, but perhaps worth editing the answer for future readers. – Tony Tannous Dec 21 '18 at 07:42
2
You can use getenv()
from cstdlib like so:
#include <cstdlib>
getenv("windir");
If you get NULL
then it's not windows.
This works since %windir%
should only be defined on windows systems. This is a cheap and dirty hack of course.

Abraham
- 8,525
- 5
- 47
- 53

Jeremy Edwards
- 14,620
- 17
- 74
- 99
-
6
-
It's a hack. You can also use getenv("OS") and check against "Windows" and "Windows_NT" but that requires some memory handling. There are other formal methods to but this function should be apart of the standard C libraries. – Jeremy Edwards Dec 06 '10 at 05:48
-
16
0
If it's runtime, you might be referring to Wine (on non-windows operating systems). If not, that's just plainly impossible. Windows binaries cannot run in other operating systems (except if they have Wine).
If it's compile time, possible duplicate: Are there any macros to determine if my code is being compiled to Windows?
(see accepted answer above)