title: Detect Windows or Linux in C, C++
body: <p>I am writing a cross platform program. I want this one program to run under both Windows and Linux, so I have two different code segments for the two platforms. If the OS is Windows, I want the first code segment to run; if it's Linux, then I want the second code segment to run.</p>
  
  <p>So I wrote the following code, but it gets an error while building both on Windows and on Linux. What should I do to solve it?</p>
  
  <pre><code>#ifdef __unix__                    /* __unix__ is usually defined by compilers targeting Unix systems */
  
      #define OS_Windows 0
      #include &lt;unistd.h&gt;
      #include &lt;stdlib.h&gt;
      #include &lt;stdio.h&gt;
      #include &lt;string.h&gt;
  
  #elif defined(_WIN32) || defined(WIN32)     /* _Win32 is usually defined by compilers targeting 32 or   64 bit Windows systems */
  
      #define OS_Windows 1
      #include &lt;windows.h&gt;
      #include &lt;stdio.h&gt;
      #include &lt;tchar.h&gt;
      #define DIV 1048576
      #define WIDTH 7
  
  #endif
  
  int main(int argc, char *argv[])
  {
      if(OS_Windows)
      {
          MEMORYSTATUSEX statex;
          statex.dwLength = sizeof (statex);
          GlobalMemoryStatusEx (&amp;statex);
  
          _tprintf (TEXT("There is  %*ld %% of memory in use.\n"),
                      WIDTH, statex.dwMemoryLoad);
  
      }
  
      else if(!OS_Windows) // if OS is unix
  
      {
          char cmd[30];
          int flag = 0;
          FILE *fp;
          char line[130];
          int memTotal, memFree, memUsed;
  
          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",&amp;TotalMem, &amp;TotalUsed, &amp;TotalFree);
          }
          pclose(fp);
  
          if(flag)
              printf("TotalMem:%d -- TotalUsed:%d -- TotalFree:%d\n",TotalMem,TotalUsed,TotalFree);
          else
              printf("not found\n");
  
      }
  
      return 0;
  }
  </code></pre>