> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-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} % 最好在导言区最后加载

\title{Subfiles 宏包示例}
\author{Overleaf}
\date{ }

\begin{document}

\maketitle

\section{引言}

\subfile{sections/introduction}

\section{第二节}

\subfile{sections/section2}

\end{document}
```

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

按文件编译需要这一行

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

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

[打开一个 `subfiles` 宏包示例](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{你好，世界！}
\begin{figure}[bh]
\centering
\includegraphics[width=3cm]{overleaf-logo}

\label{fig:img1}
\caption{Overleaf 标志}
\end{figure}

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

\end{document}
```

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

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

这里的第一条命令是

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

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

你还需要在指定 `\subfix` 时使用相对文件夹路径 `\graphicspath` 在 `introduction.tex`:

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

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

[打开一个 `subfiles` 宏包示例](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** standalone 宏包相同的功能，而且更加灵活，但语法更复杂，也更容易出错。主要区别在于每个子文件都有自己的导言区。

本节中的示例具有以下层次化文件结构：

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

### 主文件

主文件与其他多文件项目的主文件非常相似。

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

\title{Standalone 宏包示例}
\author{Overleaf}
\date{2021 年 5 月}

\begin{document}

\maketitle

\section{第一节}
\import{sections/}{introduction}

\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{一个不错的简单图示}
\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-biao-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},
]
%节点
\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};

%线条
\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 中打开这个独立 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-biao-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://overleaf-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.
