3

My Fortran 90 code on Intel compiler depends on the operating system it is running on, e.g.

if (OS=="win7") then
   do X
else if (OS=="linux") then
   do y
end if

How do I do this programmatically?

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
John Smith
  • 418
  • 7
  • 21
  • 2
    If you need a runtime check you might use `get_environment_variable("PATH",pathstring)`, then check if `pathstring` starts with `/`. – agentp Nov 19 '15 at 21:55

1 Answers1

4

You can use pre-processor directives for this task, see here and here for details:

  • _WIN32 for Windows
  • __linux for Linux
  • __APPLE__ for Mac OSX

Here is an example:

program test

#ifdef _WIN32
  print *,'Windows'
#endif
#ifdef __linux
  print *,'Linux'
#endif

end program

Make sure you enable the pre-processor by either specifying -fpp//fpp or given the file a capital F/F90 in the extension. You could do this in a central location, do define e.g. a constant describing the OS. This would avoid these Macros all over the place.

Please note that no macro for Linux is specified by gfortran. As it still defines _WIN32 on Windows, you can alternatively use #else if you just consider Linux and Windows:

program test

#ifdef _WIN32
  print *,'Windows'
#else
  print *,'Linux'
#endif

end program
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
  • 1
    Going this route http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system might be useful. Also were it me I think rather than preprocessing the Fortran I'd write a little C function that determined the OS, use preprocessing on that to get the desired info as that's what these macros are designed for, and then call it from the Fortran. – Ian Bush Nov 20 '15 at 09:43