Use chapterbib with subfile

Using subfile in LaTeX

The package subfile is a powerful tool to manage a large LaTeX project by splitting a huge tex into separate files. One example is what I am having right now: I am writing my thesis and I want to separate chapters into individual files and compile a single chapter during writing.

In main.tex:

1 2 3 4 5 6
% main.tex \usepackage{subfiles} \begin{document} \subfile{chapter1} \subfile{chapter2} \end{document}

In chapter files chapter1.tex:

1 2 3 4 5 6 7
% chapter1.tex \documentclass[main.tex]{subfiles} \begin{document} \chapter{A Good Chapter} Hello world. \bibliography{references} \end{document}

Using chapterbib in LaTeX

This is awesome, but it does not work when I need to add citations to each chapter by using chapterbib, as this is necessary in manay thesis. Due to the mechanism of chapterbib, it requires using include to use content of chapters:

In main.tex:

1 2 3 4 5 6
% main.tex \usepackage{subfiles} \begin{document} \include{chapter1} \include{chapter2} \end{document}

In addition, all chapter tex files should have document body only, even without \begin{document} and \end{document}:

In chapter files chapter1.tex:

1 2 3 4
% chapter1.tex \chapter{A Good Chapter} Hello world. \bibliography{references}

It's going to be a pain to switch between the two versions above.

So the power of macro of LaTeX comes:

Using chapterbib with subfile in LaTeX

First, define a macro in document body of main.tex as flag of building from main file, and change subfile to include:

1 2 3 4 5 6 7
% main.tex \usepackage{subfiles} \begin{document} \newcommand*{\BuildingFromMainFile}{} \subfile{chapter1} \subfile{chapter2} \end{document}

Next, check if the above flag is defined or not in chapter files. If the macro is not defined, it detects that the file is being compiled from subfile. It will add preamble automatically.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
% beginning of chapter1.tex \ifdefined\BuildingFromMainFile \else \documentclass[main.tex]{subfiles} \begin{document} \fi \chapter{A Good Chapter} Hello world. \bibliography{references} \ifdefined\BuildingFromMainFile \else \end{document} \fi

This will do the job!

Tagged with: