Detect Windows or Linux in C, C++
It's generally done like this (more or less):
#ifdef _WIN32
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#define DIV 1048576
#define WIDTH 7
#endif
#ifdef linux
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#endif
int main(int argc, char *argv[])
{
#ifdef _WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
_tprintf (TEXT("There is %*ld %% of memory in use.\n"),
WIDTH, statex.dwMemoryLoad);
#endif
#ifdef linux
char cmd[30];
int flag = 0;
FILE *fp;
char line[130];
int TotalMem, TotalFree, TotalUsed;
flag=0;
memcpy (cmd,"\0",30);
sprintf(cmd,"free -t -m|grep Total");
fp = popen(cmd, "r");
while ( fgets( line, sizeof line, fp))
{
flag++;
sscanf(line,"%*s %d %d %d",&TotalMem, &TotalUsed, &TotalFree);
}
pclose(fp);
if(flag)
printf("TotalMem:%d -- TotalUsed:%d -- TotalFree:%d\n",TotalMem,TotalUsed,TotalFree);
else
printf("not found\n");
#endif
return 0;
}
This way, only code for linux will be compiled while on a linux platform, and only windows code will be compiled on a windows platform.
How do I check OS with a preprocessor directive?
The Predefined Macros for OS site has a very complete list of checks. Here are a few of them, with links to where they're found:
Windows
_WIN32
Both 32 bit and 64 bit_WIN64
64 bit only__CYGWIN__
Unix (Linux, *BSD, but not Mac OS X)
See this related question on some of the pitfalls of using this check.
unix
__unix
__unix__
Mac OS X
__APPLE__
Also used for classic__MACH__
Both are defined; checking for either should work.
Linux
__linux__
linux
Obsolete (not POSIX compliant)__linux
Obsolete (not POSIX compliant)
FreeBSD
__FreeBSD__
Android
__ANDROID__
How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here.
Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS, tvOS, or watchOS Simulator
#elif TARGET_OS_MACCATALYST
// Mac's Catalyst (ports iOS API into Mac, like UIKit).
#elif TARGET_OS_IPHONE
// iOS, tvOS, or watchOS device
#elif TARGET_OS_MAC
// Other kinds of Apple platforms
#else
# error "Unknown Apple platform"
#endif
#elif __ANDROID__
// Below __linux__ check should be enough to handle Android,
// but something may be unique to Android.
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
Determine if Linux or Windows in C++
Use:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
static const std::string slash="\\";
#else
static const std::string slash="/";
#endif
BTW, you can still safely use this slash "/" on Windows as windows understands this perfectly. So just sticking with "/" slash would solve problems for all OSes even like OpenVMS where path is foo:[bar.bee]test.ext
can be represented as /foo/bar/bee/test.ext
.
Autodetection of OS in C/C++
I have used below code in past for checking between linux and windows
#include<stdio.h>
int main(int argc, char *argv[])
{
#ifdef _WIN32
printf("in Windows");
#endif
#ifdef linux
printf("In Linux");
#endif
return 0;
}
Usually all toolchain has their own predefined macros so you need to use those macros to detect which os is this.
List of such predefined macros.
http://sourceforge.net/p/predef/wiki/OperatingSystems/
Yes as a side note, Here detection of OS is happened using compile time macros. So according to toolchain respective macro's defination will go in build.
To detect OS version in runtime, like in java we do
System.getProperty("os.name")
Same way in C/C++ we do not have any API.
In POSIX systems using 'uname' we can get OS name.
C++ compiling on Windows and Linux: ifdef switch
use:
#ifdef __linux__
//linux code goes here
#elif _WIN32
// windows code goes here
#else
#endif
Windows and Linux with c cross platform. How to hide a function?
You can place #ifdef
#else
inside the function you want both in windows & linux. like something following
void unifiedFunction()
{
#ifdef _WIN32
//windows specific implementation goes here
#elif
//other platform like linux
#endif
}
In my repository i have a same issue when bringing platform independency. You can check my implementation here
Related Topics
How to Reduce Compile Time, and Linking Time for Visual C++ Projects (Native C++)
Configuring the Gcc Compiler Switches in Qt, Qtcreator, and Qmake
Why Does C++11 Have 'Make_Shared' But Not 'Make_Unique'
Why Is Copy Constructor Called Instead of Conversion Constructor
Why Was the Space Character Not Chosen for C++14 Digit Separators
How to Do the Equivalent of Memset(This, ...) Without Clobbering the Vtbl
How to Allocate a 2D Array of Pointers in C++
Pointer Interconvertibility VS Having the Same Address
The New Keyword "Auto"; When Should It Be Used to Declare a Variable Type
Which C++ Signals/Slots Library Should I Choose
Constexpr Const VS Constexpr Variables
How to Alter a Float by Its Smallest Increment (Or Close to It)
Will a "Variablename;" C++ Statement Be a No-Op at All Times
C++ Global Variable Declaration
C++ & Boost: Encode/Decode Utf-8