Include line problem

Wishing to include a file ~/barfoo.f90 in a program ~/Jfh/foobar.f90 I wrote this to test how include lines work in my Linux system:

program foobar
  include '~/barfoo.f90'
end program

Unfortunately neither gfortran nor ifort could open the included file. But if I changed ~ to .. in the include line both compilers compiled and ran it. I would have preferred ~ because I might sometimes want to use include lines in programs deeper in the directory tree. Can it be done?

Both compilers allow the INCLUDE search path to be specified on the command line.

For gfortran see Directory Options (The GNU Fortran Compiler)

For Intel Fortran

Thank you @DavidB and @kargl - problem solved. The happiest way would have been for an include file_name line to allow a non-constant file_name but I suspect that’s not coming in F202Y.

The reason for the difference is that ~ is expanded by a shell (usually to the same thing as the $HOME environment variable), while .. and . are part of the file system. If you do an ls, then you don’t see them because they are invisible (they begin with periods), but if you do ls -a to show invisible files, then you do see them. Every directory has those files defined automatically by the file system, you do not need to define them yourself (e.g. as hard or soft links).

$ mkdir xxx
$ ls -a xxx
.  ..

So in fortran, for example in an open statement, if you want to access files relative to your home directory, you would typically do something like the following:

PROGRAM test_getenv
  CHARACTER(len=255) :: homedir
  CALL get_environment_variable("HOME", homedir)
  WRITE (*,*) TRIM(homedir)

which is the example in the gfortran documentation. You would then reference your files relative to your home directory as, for example,

TRIM(homedir) // '/myfile'
TRIM(homedir) // '/mydir/myfile'

As you have determined, this does not work with fortran INCLUDE, which requires a literal constant, not a fortran variable or a parameter.

There are a few alternatives for the INCLUDE case. Some compilers allow the search path for INCLUDE to be specified through an environment variable or through a command line option. There is also the de facto standard preprocessor #include and macro substitution that can be used in a variety of ways.