If you are interested in a basic tutorial for compiling FORTRAN using SCons, try this page. Here is a simple setup for a multiple directory Fortran 90 project, along with some tips on using scons with Fortran. Fortran 90 is a little more complicated to compile than C, in the sense that compiling a single source file can lead to one or more module files, in addition to an object file. Other source files can depend on these module files. To make things worse, there is no standard naming scheme for module files, or standard flags for stipulating where module files should end up.

The SConstruct File

The example project has a simple directory layout:

The source is kept in the directories subdir1 and subdir2. The build directory is used to store object and module files.

The SConstruct file creates variables for the list of source directories, and then builds up a module search path for the compiler:

   1 #
   2 # Paths
   3 #
   4 subdirs = ['subdir1', 'subdir2']
   5 modpath = map(lambda d: os.path.join('#/build',d), subdirs)

For each source directory, a corresponding build directory is created under build. The modpath variable is assigned to a list of these build directories. The module files will be kept along with the object files in build directories, and need to be in the module search path used by the compiler.

The module path is passed to the scons environment as follows:

   1 #
   2 # Environment
   3 #
   4 env = Environment(
   5     F90PATH = modpath,
   6     FORTRAN = 'g95',
   7     FORTRANMODDIRPREFIX = '-fmod=',
   8     FORTRANMODDIR = '${TARGET.dir}',
   9     LINK = 'g95')

The modpath list is passed to the environment via F90PATH. In this example, the g95 compiler has been used, but other compilers work equally well.

The FORTRANMODDIRPREFIX should be set to the command option of the fortran compiler that stipulates where module files should be moved after a source file has been compiled. G95 uses -fmod for this, but every compiler has a different option, and some have no option at all (more on that below).

The FORTRANMODDIR is set to ${TARGET.dir}. This gets substituted with the directory of the target file, namely the build directory. The net result is that the module files resulting from a compilation will end up together with the emitted object file.

LINK has also been set to g95. Most Fortran compilers require you to link with particular Fortran libraries, and the easiest way to achieve this is not to use ld for linking, but the Fortran compiler itself, which automatically links in the libraries.

Calling the SConscript files in the source subdirectories is pretty much the same as for any other programming language. Here is how it is done in the example:

   1 #
   2 # Build dependency tree
   3 #
   4 allobjs = []
   5 for sd in subdirs:
   6     buildDir = os.path.join('build',sd)
   7     consFile = os.path.join(buildDir,'SConscript')
   8     env.BuildDir(buildDir, sd)
   9     allobjs = allobjs + env.SConscript( consFile, exports = ['env','Glob'])

There is one important discrepency between Fortran 90 and other languages: the SConscript file typically returns a list of not only object files, but also module files. If you blindly pass this list to a Program method, as you would for a C program, for example, you will get a link error because the linker does not know what to do with the module files. To avoid this, you need to 'weed out' the module files before passing the list to the Program method, like so:

   1 #
   2 # Remove any mod files. These should not be passed to the linker.
   3 #
   4 objs = filter(lambda o: str(o)[-4:] != '.mod', allobjs)
   5 
   6 ...
   7 
   8 #
   9 # Build program
  10 #
  11 env.Program('test.x', ['main.f90'] + objs )

As eluded to above, some compilers (eg. MIPS f90 on Irix) don't have a flag to stipulate the directory that module files should be moved to when a source file is compiled. The module files get put in the current working directory, which would be the root directory of your project. The problem is that scons expects module files to be stored in the build directories. If you rerun scons, it will not find the module files, and will rebuild all sources in any way connected to the modules. To avoid this, you really do need to move the module files to the appropriate build directories.

One way to do this is to add a post action for each object file target returned by the SConscripts:

   1 #
   2 # Add an action to move any module files
   3 #
   4 def moveModFiles(target=None, source=None, env=None):
   5     import glob, os, os.path
   6     targetdir = target[0].dir
   7     for t in target:
   8         if t.name[-4:] == '.mod':
   9             os.rename(t.name,os.path.join(str(targetdir),t.name))
  10 
  11 env.AddPostAction(objs, moveModFiles)

The moveModFiles function simply looks for any module files passed in target, which is a list of the object and module files corresponding to the source file passed, and moves them to the build directory.

Below is the full SConstruct file for the example. Note that this variant does not use the -fmod flag of g95, but uses a post action to move module files to the build directory. This is purely for demonstration purposes; if you were really using g95, you would be better to use the -fmod flag.

   1 #!/usr/bin/env python
   2 import os, os.path, sys, fnmatch
   3 
   4 #
   5 # Functions
   6 #
   7 def Glob(match):
   8     """Similar to glob.glob, except globs SCons nodes, and thus sees
   9     generated files and files from build directories.  Basically, it sees
  10     anything SCons knows about.  A key subtlety is that since this function
  11     operates on generated nodes as well as source nodes on the filesystem,
  12     it needs to be called after builders that generate files you want to
  13     include."""
  14     def fn_filter(node):
  15         fn = str(node)
  16         return fnmatch.fnmatch(os.path.basename(fn), match)
  17 
  18     here = Dir('.')
  19 
  20     children = here.all_children()
  21     nodes = map(File, filter(fn_filter, children))
  22     node_srcs = [n.srcnode() for n in nodes]
  23 
  24     src = here.srcnode()
  25     if src is not here:
  26         src_children = map(File, filter(fn_filter, src.all_children()))
  27         for s in src_children:
  28             if s not in node_srcs:
  29                 nodes.append(File(os.path.basename(str(s))))
  30 
  31     return nodes
  32 
  33 #
  34 # Paths
  35 #
  36 subdirs = ['subdir1', 'subdir2']
  37 modpath = map(lambda d: os.path.join('#/build',d), subdirs)
  38 
  39 #
  40 # Environment
  41 #
  42 env = Environment(
  43     F90PATH = modpath,
  44     FORTRAN='g95',
  45     LINK = 'g95')
  46 
  47 #
  48 # Build dependency tree
  49 #
  50 allobjs = []
  51 for sd in subdirs:
  52     buildDir = os.path.join('build',sd)
  53     consFile = os.path.join(buildDir,'SConscript')
  54     env.BuildDir(buildDir, sd)
  55     allobjs = allobjs + env.SConscript( consFile, exports = ['env','Glob'])
  56 
  57 #
  58 # Remove any mod files. These should not be passed to the linker.
  59 #
  60 objs = filter(lambda o: str(o)[-4:] != '.mod', allobjs)
  61 
  62 
  63 #
  64 # Add an action to move any module files
  65 #
  66 def moveModFiles(target=None, source=None, env=None):
  67     import glob, os, os.path
  68     targetdir = target[0].dir
  69     for t in target:
  70         if t.name[-4:] == '.mod':
  71             os.rename(t.name,os.path.join(str(targetdir),t.name))
  72 
  73 env.AddPostAction(objs, moveModFiles)
  74 
  75 #
  76 # Build program
  77 #
  78 env.Program('test.x', ['main.f90'] + objs )

The SConscript File

The SConscript file for this example is very simple. Here it is:

   1 #!/usr/bin/env python
   2 
   3 Import('env','Glob')
   4 
   5 sources = Glob('*.f90') + Glob('*.f')
   6 objs = env.Object(sources)
   7 
   8 Return('objs')

What you'll notice is that it uses a function Glob, which is imported from the SConstruct script. This Glob function is taken from the page BuildDirGlob; it allows you to do a glob for source files from within the corresponding build directory. In this case it is used to get a list of all files with the extension .f90 or .f.

A list of Objects are made in the usual way, and returned. Note that these Objects include the module files, in addition to the real object files.

Other Problems

Fortran is a case-insensitive language, so the case used in module names is irrelevant. Most compilers create module files with lowercase names, such as somemodule.mod, but others use uppercase (ie SOMEMODULE.mod). At this point, scons assumes module files will be in lowercase. Hopefully options will be added in the future to allow for either, but in the meantime there is a simple workaround if you are stuck with a compiler using uppercase: ensure that both module file variants are created.

You can do this with a post action that copies the module file created by the compiler, and uses the lowercase naming scheme for the new copy. Here is a variation on the moveModFiles function given earlier that creates the two module file variants:

   1 def MoveModFiles(target=None, source=None, env=None):
   2     """
   3     Moves mod files to build directory. Also creates upper/lower-case versions.
   4     This is needed on SGI, for example.
   5     """
   6     import os, os.path, shutil
   7     targetdir = target[0].dir
   8     for t in target:
   9         namebase, nameext = os.path.splitext(t.name)
  10         modfilename = namebase.upper() + nameext
  11         lowermodfilename = namebase.lower() + nameext
  12         if modfilename[-4:] == '.mod':
  13             builddirupperpath = os.path.join(str(targetdir),modfilename)
  14             builddirlowerpath = os.path.join(str(targetdir),lowermodfilename)
  15             os.rename(modfilename, builddirupperpath)
  16             shutil.copy(builddirupperpath, builddirlowerpath)
  17 
  18 ...
  19 
  20 env.AddPostAction(objs, MoveModFiles)

As you can see, it is simply a question of duplicating the uppercase file, and using the lowercase naming scheme for the duplicate. Note that you can't just move the uppercase file, because the compiler will expect it to exist. In effect, the uppercase file is for the compiler, and the lowercase file is for scons.

Options specific to Intel FORTRAN compiler:

MultipleDirectoryFortranBuild (last edited 2011-08-30 18:43:52 by 208-76-193-149)