Latex as a document system and markup language is very well suited for creating large documents. Working with a big, single file however remains an hassle, whatever its content. Fortunately, Latex supports splitting your document in several files.

Two commands will make your life a lot easier:

\input{file.tex}
\include{file.tex}

Although slightly different, both allow to include content from an external file inside your latex code. This is exactly what you want when you’re writing a book or a long article. You can split your content over multiple files and simply include them in the main document.

Although certainly superior to working with a single monolithic file, this approach too has its disadvantages. I personally like to compile my document once in a while too see how it looks or whether I made some mistakes. This is not an option when working outside the main file. You have to recompile the main document each and every time for this.

Subfiles

As with almost any problem you might experience with Latex, someone already experienced it before you and found or created a solution. In this case, the solution is a package called subfiles. This package allows you to define the main document as its documentclass consequently making it possible to compile the included file by itself.

Simply include the package in your main document and use the command \subfile{filename} inside your document.

\documentclass[11pt]{book}
\usepackage{subfiles}

\begin{document}
...
\subfile{finename}
...
\end{document}

The subfile itself contains a custom documentclass, referring to the main document as shown below.

\documentclass[main.tex]{subfiles}

\begin{document}
...
\end{document}

Subfiles with Subdirectories

Usually, you’ll want to put your subfiles in a different directory than the main document. To do so, you’ll have to keep some things in mind. First off, you’ll have to update the path to the main document in the subfile’s document class.

The example below illustrates the case where the file main.tex is located in the directory one level above the subfile.

\documentclass[../main.tex]{subfiles}

Secondly, your main document as well as your subfile might include relative paths to external content, for example images. Although no problem for the main document, this causes broekn paths for the subfiles, because their relative location is now different.

There are two general solutions:

  • Use a package’s built-in support for defining path. The graphicx package for example allows you to define multiple paths.
\graphicspath{{figures/}{../figures/}}
  • Use absolute paths, something I do not recommend. Chances are you’ll want to compile your document on another device one day and chances are slim the paths will be identical.
  • Use a custom command instead of the path itself. Alter it when compiling subfiles. Admittingly this is a bit of a hassle, but it’s a very general and foolproof solution.