> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/wen-dang-jie-gou/08-multi-file-latex-projects.md).

# 多文件 LaTeX 项目

## 引言

在 [大型 LaTeX 文档](/latex/zh-cn/wen-dang-jie-gou/07-management-in-a-large-project.md) 通常会有多个 `.tex` 文件，每个章节或节对应一个，然后把它们合并生成一个单一输出。这有助于保持内容有条理，也更容易调试文档，但随着文档变大，编译会更耗时。这可能会让人沮丧，因为通常每次只想处理某个特定文件。

克服这一点的自然方法是分别编译每个文件。有两个主要宏包允许在多文件项目中编译单个文件。你选择哪一个取决于你的需求。

* 使用 [该 **subfiles** 宏包](#the-subfiles-package) 你可以独立编译每个子文件，而且每个子文件都会自动使用主文件中的导言区。
* 使用 [该 **standalone** 宏包](#the-standalone-package) 每个子文件都作为独立文件工作，之后这些子文件可以合并到一个主文档中，由主文档提取各自的导言区。如果你需要在多个文档中复用同一个文件，这会特别有用，TikZ 图就是一个很好的例子。

## Overleaf .tex 文件中关于 \documentclass 的说明

正如下面的视频片段所示，即使你已经设置了项目的主 `.tex` 文件，你也可以选择另一个文件进行编译——前提是它包含一个 `\documentclass` 声明。不过，为了确保项目中的所有元素都能正确编译——例如术语表、访问到 `.bib` 文件等——我们强烈建议你只编译项目根目录中的文件。

{% embed url="<https://videos.ctfassets.net/nrgyaltdicpt/U2nGfRx9NwNGX0vWXNebP/1ca4b9a4b2f36d5ca9c0dbaa87f44bfa/maincompile.mp4>" %}

## subfiles 宏包

这个宏包适用于大多数情况，真的很容易使用。

本节中的示例具有如下层级文件结构：

![CompileSubfilesEx1OverleafV2.png](/files/ad1a8416e65b09b5bf15586366687c06858552a3)

### 主文件

在主文件中需要两个特殊命令。

```latex
\documentclass{article}
\usepackage{graphicx}
\graphicspath{{images/}}

\usepackage{blindtext}

\usepackage{subfiles} % Best loaded last in the preamble

\title{Subfiles package example}
\author{Overleaf}
\date{ }

\begin{document}

\maketitle

\section{Introduction}

\subfile{sections/introduction}

\section{Second section}

\subfile{sections/section2}

\end{document}
```

![CompileSubfilesEx1aOverleafV2.png](/files/74f7fcd87dca089eb4b741131a93a7707ce7f37d)

按文件编译需要这一行

```latex
\usepackage{subfiles}
```

在导言区中，这会启用 `subfiles` 宏包。然后每个外部子文件都必须通过命令导入 `\subfile{}`。在这个示例中，文件 `introduction.tex` 和 `section2.tex` 被从 `sections` 文件夹导入到主文件中。注意，文件扩展名不是必须的。

[打开一个 `subfiles` 在 Overleaf 中的宏包示例](https://www.overleaf.com/project/new/template/19626?id=66392908\&templateName=Subfiles+package+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

### 子文件

一旦你设置好主文件，每个子文件都必须具有特殊的结构。

```latex
\documentclass[../main.tex]{subfiles}
\graphicspath{{\subfix{../images/}}}
\begin{document}
\textbf{Hello world!}
\begin{figure}[bh]
\centering
\includegraphics[width=3cm]{overleaf-logo}

\label{fig:img1}
\caption{Overleaf logo}
\end{figure}

你好，这里有一些没有意义的文本……

\end{document}
```

![CompileSubfilesEx2OverleafV2.png](/files/ea373cc4e96bdbb5b3ef8d0c9237e3851f8fa017)

现在这个文件可以作为独立文件编译，文档类以及其余导言区都将与主文档中定义的相同。

这里的第一个命令是

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

括号中的参数 `../main.tex`，它是到主文档的相对路径。在这种情况下，该文件 `introduction.tex` 位于文件夹 `sections`，因此该文件 `main.tex` 比当前文件夹高一级（这就是 `../` 的含义）。

你还需要使用 `\subfix` 命令，并在指定时附上相对文件夹路径 `\graphicspath` .bib 文件中插入一个 % `introduction.tex`:

```latex
\graphicspath{{\subfix{../images/}}}
```

然后实际内容要输入在 `\begin{document}` 和 `\end{document}`。该环境之外的所有内容都会被忽略，或者更准确地说，会被视为导言区的一部分。避免在文件顶部和底部留下空行。

[打开一个 `subfiles` 在 Overleaf 中的宏包示例](https://www.overleaf.com/project/new/template/19626?id=66392908\&templateName=Subfiles+package+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## standalone 宏包

宏包 **standalone** 提供与……相同的功能 **subfiles** 并且更灵活，但语法更复杂，也更容易出错。主要区别在于每个子文件都有自己的导言区。

本节中的示例具有如下层级文件结构：

![CompileSubfilesEx3OverleafV2.png](/files/fb9633ddcfd685fd87ebb0f52d8120bb184367a2)

### 主文件

主文件与其他任何多文件项目都非常相似。

```latex
\documentclass{article}
\usepackage[subpreambles=true]{standalone}
\usepackage{import}

\title{Standalone package example}
\author{Overleaf}
\date{May 2021}

\begin{document}

\maketitle

\section{First section}
\import{sections/}{introduction}

\section{Second section}
\import{sections/}{section2}

\end{document}
```

![CompileSubfilesEx3Overleaf.png](/files/8007ea58217908f583b7347346680f3716db883f)

这一行

```latex
\usepackage[subpreambles=true]{standalone}
```

启用 **standalone** 宏包，它应尽早放在文档中。方括号中的参数会告诉 LaTeX 从每个子文件导入导言区（宏包只会导入一次）；如果省略，请确保主文档导言区中包含子文件正常工作所需的所有命令。需要小心，因为不同导言区之间可能存在不兼容。

在主文档正文中，每个子文件都通过……导入 `\import{}{}`。标准的 `\input{}` 命令也可以使用，但本示例中的这个更推荐用于 [管理大型项目](/latex/zh-cn/wen-dang-jie-gou/07-management-in-a-large-project.md) 因为它可以防止嵌套文件中的错误。

[打开一个……的示例 `standalone` Overleaf 中的宏包](https://www.overleaf.com/project/new/template/19636?id=66440758\&templateName=Standalone+package+example\&latexEngine=pdflatex\&texImage=\&mainFile=)

### 子文件

每个子文件都必须有自己的导言区，并导入作为独立文档运行所需的所有宏包。

```latex
\documentclass[class=article, crop=false]{standalone}
\usepackage[subpreambles=true]{standalone}
\usepackage{import}
\usepackage{blindtext}

\begin{document}
下面将渲染一个 TikZ 图

\begin{figure}[ht]
\centering
\subimport{../}{diagram.tex}
\label{fig:tikzexample}
\caption{A nice simple diagram}
\end{figure}

\blindtext
\end{document}
```

![CompileSubfilesEx4OverleafV2.png](/files/0974c47b100f20e75f3d156f6201a938c236fcef)

子文件中的第一行是

```latex
\documentclass[class=article, crop=false]{standalone}
```

这声明这是一个要与……一起使用的文件 **standalone** 宏包，括号内有两个可选参数。

* `class=article`。设置 `article` 作为底层类，也可以使用其他类：book、report 等（beamer 除外）。
* `crop=false`。如果省略此选项，输出将被裁剪到最小尺寸。

接下来的命令不是必需的

```latex
\usepackage[subpreambles=true]{standalone}
```

但在这个示例中必须使用，因为这里有一个嵌套的 **standalone** 文件。一个 [TikZ 图](/latex/zh-cn/tu-xing-he-biao-ge/05-tikz-package.md) 通过……插入 [`\subimport{../}{diagram.tex}`](/latex/zh-cn/wen-dang-jie-gou/07-management-in-a-large-project.md#importing-files)，你可以在下面看到文件 "diagram.tex" 的内容：

```latex
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}

\begin{tikzpicture}[
roundnode/.style={circle, draw=green!60, fill=green!5, very thick, minimum size=7mm},
squarednode/.style={rectangle, draw=red!60, fill=red!5, very thick, minimum size=5mm},
]
%Nodes
\node[squarednode]      (maintopic)                              {2};
\node[roundnode]        (uppercircle)       [above=of maintopic] {1};
\node[squarednode]      (rightsquare)       [right=of maintopic] {3};
\node[roundnode]        (lowercircle)       [below=of maintopic] {4};

%Lines
\draw[->] (uppercircle.south) -- (maintopic.north);
\draw[->] (maintopic.east) -- (rightsquare.west);
\draw[->] (rightsquare.south) .. controls +(down:7mm) and +(right:7mm) .. (lowercircle.east);

\end{tikzpicture}
\end{document}
```

[打开 Overleaf 中的这个 Standalone TikZ 示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Standalone+TikZ+example\&snip=%5Cdocumentclass%7Bstandalone%7D%0A%5Cusepackage%7Btikz%7D%0A%5Cusetikzlibrary%7Bpositioning%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Cbegin%7Btikzpicture%7D%5B%0Aroundnode%2F.style%3D%7Bcircle%2C+draw%3Dgreen%2160%2C+fill%3Dgreen%215%2C+very+thick%2C+minimum+size%3D7mm%7D%2C%0Asquarednode%2F.style%3D%7Brectangle%2C+draw%3Dred%2160%2C+fill%3Dred%215%2C+very+thick%2C+minimum+size%3D5mm%7D%2C%0A%5D%0A%25Nodes%0A%5Cnode%5Bsquarednode%5D++++++%28maintopic%29++++++++++++++++++++++++++++++%7B2%7D%3B%0A%5Cnode%5Broundnode%5D++++++++%28uppercircle%29+++++++%5Babove%3Dof+maintopic%5D+%7B1%7D%3B%0A%5Cnode%5Bsquarednode%5D++++++%28rightsquare%29+++++++%5Bright%3Dof+maintopic%5D+%7B3%7D%3B%0A%5Cnode%5Broundnode%5D++++++++%28lowercircle%29+++++++%5Bbelow%3Dof+maintopic%5D+%7B4%7D%3B%0A%0A%25Lines%0A%5Cdraw%5B-%3E%5D+%28uppercircle.south%29+--+%28maintopic.north%29%3B%0A%5Cdraw%5B-%3E%5D+%28maintopic.east%29+--+%28rightsquare.west%29%3B%0A%5Cdraw%5B-%3E%5D+%28rightsquare.south%29+..+controls+%2B%28down%3A7mm%29+and+%2B%28right%3A7mm%29+..+%28lowercircle.east%29%3B%0A%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

![CompileSubfilesEx5.png](/files/54f650b7b3c890b85f55902e9e392c4e9e4bce94)

这是……中的主要特性 **standalone**，你可以将此文件导入任何其他文档并重复利用代码。例如，这个图之后可以在演示文稿中直接使用，无需进一步修改。

[打开一个……的示例 `standalone` Overleaf 中的宏包](https://www.overleaf.com/project/new/template/19636?id=66440758\&templateName=Standalone+package+example\&latexEngine=pdflatex\&texImage=\&mainFile=)

## 进一步阅读

更多信息请参见

* [大型项目中的管理](/latex/zh-cn/wen-dang-jie-gou/07-management-in-a-large-project.md)
* [章节和公式交叉引用](/latex/zh-cn/wen-dang-jie-gou/03-cross-referencing-sections-equations-and-floats.md)
* [索引](/latex/zh-cn/wen-dang-jie-gou/04-indices.md)
* [术语表](/latex/zh-cn/wen-dang-jie-gou/05-glossaries.md)
* [超链接](/latex/zh-cn/wen-dang-jie-gou/09-hyperlinks.md)
* [页码编号](/latex/zh-cn/ge-shi-hua/03-page-numbering.md)
* [单面和双面文档](/latex/zh-cn/ge-shi-hua/08-single-sided-and-double-sided-documents.md)
* [多栏排版](/latex/zh-cn/ge-shi-hua/09-multiple-columns.md)
* [段落格式](/latex/zh-cn/ge-shi-hua/04-articles-how-to-change-paragraph-spacing-in-latex.md)
* [页面大小和页边距](/latex/zh-cn/ge-shi-hua/07-page-size-and-margins.md)
* [计数器](/latex/zh-cn/ge-shi-hua/10-counters.md)
* [页边注释](/latex/zh-cn/ge-shi-hua/15-margin-notes.md)
* [粗体、斜体和下划线](/latex/zh-cn/latex-ji-chu/03-bold-italics-and-underlining.md)
* [字体大小、字体族和样式](/latex/zh-cn/zi-ti/01-font-sizes-families-and-styles.md)
* [字体类型](/latex/zh-cn/zi-ti/02-font-typefaces.md)
* [使用 XeLaTeX 支持现代字体](/latex/zh-cn/zi-ti/03-xelatex.md)
* [国际语言支持](/latex/zh-cn/yu-yan/03-international-language-support.md)
* [字体大小、字体族和样式](/latex/zh-cn/zi-ti/01-font-sizes-families-and-styles.md)
* [编译大型项目](/latex/zh-cn/zhi-shi-ku/038-fixing-and-preventing-compile-timeouts.md#compiling-big-projects)
* [插入图片](/latex/zh-cn/geng-duo-zhu-ti/27-inserting-images.md)
* [TikZ 宏包](/latex/zh-cn/tu-xing-he-biao-ge/05-tikz-package.md)
* [编写你自己的宏包](/latex/zh-cn/lei-wen-jian/03-writing-your-own-package.md)
* [编写你自己的类](/latex/zh-cn/lei-wen-jian/04-writing-your-own-class.md)
* [该 **subfiles** 包文档](http://repositorios.cpai.unb.br/ctan/macros/latex/contrib/subfiles/subfiles.pdf)
* [该 **standalone** 包文档](http://repositorios.cpai.unb.br/ctan/macros/latex/contrib/standalone/standalone.pdf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/wen-dang-jie-gou/08-multi-file-latex-projects.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
