Separating Source and Build Directories

It's often useful to keep any built files completely separate from the source files. This is usually done by creating one or more separate build directories that are used to hold the built objects files, libraries, and executable programs, etc. for a specific flavor of build. SCons provides two ways to do this, one through the SConscript function that we've already seen, and the second through a more flexible BuildDir function.

Specifying a Build Directory as Part of an SConscript Call

The most straightforward way to establish a build directory uses the fact that the usual way to set up a build hierarchy is to have an SConscript file in the source subdirectory. If you then pass a build_dir argument to the SConscript function call:

      SConscript('src/SConscript', build_dir='build')

SCons will then build all of the files in the build subdirectory:

      % ls src
      SConscript  hello.c
      % scons -Q
      cc -o build/hello.o -c build/hello.c
      cc -o build/hello build/hello.o
      % ls build
      SConscript  hello  hello.c  hello.o

But wait a minute--what's going on here? SCons created the object file build/hello.o in the build subdirectory, as expected. But even though our hello.c file lives in the src subdirectory, SCons has actually compiled a build/hello.c file to create the object file.

What's happened is that SCons has duplicated the hello.c file from the src subdirectory to the build subdirectory, and built the program from there. The next section explains why SCons does this.