和C语言建立工程实现多文件编译的初衷类似,当编写的LaTeX文档过长,我们希望能将其划分为多个小文档分别进行修改调试,使结构更加清晰,组织代码更加方便。
可用的命令有三条,分别是:
\input
\include
\includeonly
下面分别介绍这三条命令。
1、\input{xxx}
单纯地将xxx.tex内容导入进主文件中,不分页;
可放在导言区或正文区;
各分文件加入宏命令后可以分别编译,但编码自动从1开始,可能造成交叉引用混乱。
2、\include{xxx}
分页显示内容,适于book类分chapter编写;
只能放置在正文区,往往与\includeonly合用;
总是显示正确的编码顺序。
3、\includeonly{a,b,c,...}
放在导言区;
与\ include合用,指定部分或全部\include内容参与编译。
举例如下:
1、使用\input命令
%main.tex
\documentclass[12pt,a4paper]{article}
\def\allfiles{}
\begin{document}
% paper title
\title{How to \textbf{compile} in files}
\maketitle
\input{abstract}
\input{introduction}
\input{implement}
\input{reference}
\end{document}
%abstract.tex
\ifx\allfiles\undefined
\documentclass[12pt,a4paper]{article}
\begin{document}
\fi
\section*{Abstract}
This is abstract.
\ifx\allfiles\undefined %如果位置放错,可能出现意外中断
\end{document}
\fi
%introduction.tex
\ifx\allfiles\undefined
\documentclass[12pt,a4paper]{article}
\begin{document}
\fi
\section{Introduction}
This is introduction. It's the first part.
\ifx\allfiles\undefined
\end{document}
\fi
%implement.tex
\ifx\allfiles\undefined
\documentclass[12pt,a4paper]{article}
\begin{document}
\fi
\section{Inplement}
This is inplement.
If you compile it seperately, it's number is 1, else 2.
\ifx\allfiles\undefined
\end{document}
\fi
%reference.tex
\ifx\allfiles\undefined
\documentclass[12pt,a4paper]{article}
\begin{document}
\fi
\section{Reference}
This is reference.
If you compile it seperately, it's number is 1, else 3.
\ifx\allfiles\undefined
\end{document}
\fi
2、联合使用\include和\includeonly
和1中类似,只需要将\input命令修改为\include命令,在导言区加入\includeonly。
%main.tex
\documentclass[12pt,a4paper]{article}
\includeonly{abstrct,introduction,implement,reference}%根据需要删减
\begin{document}
% paper title
\title{How to \textbf{compile} in files}
\maketitle
\include{abstract}
\include{introduction}
\include{implement}
\include{reference}
\end{document}
其余文件只需要注释掉宏命令即可。