Custom format file and subfiles

pdflatex -fmt preamble sub.tex

The error is self-explanatory: In this way you provide two \documentclass, that is not the same that left to the subfile class to be replaced by the (non-existent in this case) document class of main.tex. This is the same that compile a single file with this wrong code:

\documentclass[a4paper,12pt]{article}
\usepackage{subfiles}
\usepackage{lipsum}
\documentclass[main]{subfiles}  
\documentclass{article}
\begin{document}
\lipsum[1]
\end{document}

The possible solutions:

1) Left \documentclass in main.tex. Then, the problem will be that in preamble.tex there are \usepackage commands that must be used after the \documentclass (of main.tex), not before. Fortunately this command can be replaced by \RequirePackage. So, this preamble.tex produce a working preamble.fmt

\RequirePackage{subfiles}
\RequirePackage{lipsum}
%%further packages and custom commands

The main.tex should be then:

\documentclass[a4paper,12pt]{article} % 
\begin{document}
Here are the contents of my subfile: 
\subfile{sub}
\end{document}

2) Alternatively, in case of trouble with some code, resign to a non-precompiled preamble (fused in main.tex or included with \input{preamble}).

3) If the precompiled preamble is indispensable (=noticeable seep up), in case of trouble I guess that should be possible use a mix of both approaches (that is, a pre-compiled/pre-document preamble plus the conventional non-precompiled/post-document preamble with the problematic code). However, this look like the typical situations in which I regret ignore the KISS principle ("Keep it simple, stupid").


Try adding the docmute package to the preamble format file instead of subfiles, and a regular article class in the sub file. the problem is that latex only allows one documentclass per document, and you are adding a second in the subfile; docmute redefines the documentclass command and the document environment, so that the preambles of the included files are ignored. so, using docmute and standard include should solve the problem