> 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-tw/zhi-shi-ku/033-cross-referencing-with-the-xr-package-in-overleaf.md).

# 在 Overleaf 中使用 xr 套件進行交互參照

## 概覽

該 [`xr` 套件](https://ctan.org/pkg/xr?lang=en) 讓你建立指向外部 LaTeX 文件中公式、圖形、表格等的交叉參照，前提是那些文件是 *獨立文件。* 獨立的 LaTeX 文件是指可以被編譯的文件，因為它包含 `\documentclass{...}` 語句以及 `\begin{document}`...`\end{document}` 結構。

### 用法摘要

1. 撰寫 `\usepackage{xr}` 在需要交叉參照外部 LaTeX 檔案中內容的 LaTeX 檔案前言區中。
2. 請使用 `xr` 套件命令 `\externaldocument{filename}` 來指定你要交叉參照內容的外部文件。

該 `xr` 套件會透過使用包含於……中的交叉參照標籤來運作 `.aux` 外部 LaTeX 文件編譯時產生的檔案。

### 交叉參照如何運作（簡短摘要）

若要在 LaTeX 文件中交叉參照某個項目，你需要：

1. 為它指定一個唯一識別碼， `some_string`，使用 `\label` 命令：

```latex
\label{some_string}
```

3. 在你想要引用該元素的位置，你需要寫

```latex
\ref{some_string}
```

簡單來說，LaTeX 透過將資料寫入一個名為 `filename.aux` 其中 `filename` 是主 `.tex` 被編譯的檔案名稱。

為了讓這個流程運作，LaTeX 文件必須至少編譯兩次：第一次編譯 *會產生* 參照資料——將其寫入 `filename.aux`。在第二次編譯時，LaTeX *讀取* `filename.aux` 以解析參照，提供資料來取代 `\ref{some_string}`.

* 如需更多關於交叉參照的細節，請參閱 Overleaf 文章 [交叉參照章節、公式與浮動體](/latex/zh-tw/wen-jian-jie-gou/03-cross-referencing-sections-equations-and-floats.md).

## 不需要 xr 套件的專案

大型 LaTeX 專案，例如書籍或長篇報告，通常會拆分成一系列較小的 `.tex` 檔案，每章一個，而每章的 `.tex` 檔案會使用 `\input` 或 `\include`。通常，這些章節並非獨立文件：你無法編譯單獨的章節，因為它們不包含 `\documentclass{...}` 語句或 `\begin{document}...\end{document}` 結構。這些章節是用來 *納入* 到一個「容器」文件中，而該文件 *可以* 可被編譯。在這種情況下，對文件元素的交叉參照——在任何單獨的章節檔內——都可正常進行：你不需要使用 `xr` 套件。

若要探索大型專案範例，你可以 [在 Overleaf 中開啟此範例。](https://www.overleaf.com/project/new/template/20618?id=70769185\&templateName=Managing+a+large+project+on+Overleaf\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## 需要 xr 套件的專案範例

假設你有一組獨立的 LaTeX 文件，例如一組 N 篇文章： `article1.tex`, `article2.tex` ... `articleN.tex`。這些文章都可以分別編譯，而且它們很可能是使用各式各樣的文件類別、套件等所撰寫。

現在想像你要使用 LaTeX 來撰寫這些文章的概覽或摘要——我們將把我們的檔案稱為 `summary.tex`。我們的摘要需要引用那些各自獨立的 N 篇文章中的章節、圖形、表格、公式等。我們該怎麼做？

該 `xr` 套件讓你可以這麼做：它使 `summary.tex` 能使用由任何獨立的 `article*.tex` .bib 檔案。

### 關於 .aux 檔案的說明

* 注意，這裡我們使用星號（`*`）作為 1 到 N 之間任意數字的佔位符。

編譯任何獨立檔案 `article1.tex`, `article2.tex` ... `articleN.tex` 會使 LaTeX 產生對應的 `article*.aux` (\*\*`aux`\*\*附屬）檔案，其中除其他項目外，還包含產生交叉參照所需的標籤資料。

如果任何 `article*.tex` 檔案被編輯——例如變更、新增或移除標籤（`\label{...}`）——對應的 `article*.tex` 檔案必須重新編譯，以更新相關的 `article*.aux` 檔案。

偵測對……的變更 `article*.tex`，並在之後重新編譯它們，可以在 Overleaf 上透過使用適當的……自動化 `latexmkrc` 檔案中使用的指令。

## 如何在 Overleaf 上使用 xr

我們將使用多文章範例的簡化版本；特別是，我們會示範如何透過一個 `latexmkrc` 檔案 [由 John Collins 提供給 Overleaf 的](#code-for-latexmkrc) ([維護者 `latexmk`](https://ctan.org/pkg/latexmk?lang=en)).

### 我們範例中使用的檔案

我們的範例使用以下檔案：

* `**summary.tex**`：這是我們的概覽文件。我們需要它來參照包含於 `article1.tex`中的內容，例如圖形與章節。
  * `summary.tex` 載入 `xr` 套件，並使用 `\externaldocument{article1}` 來指定來自 `article1.aux` 的參照資料應被使用。
* `**article1.tex**`：一篇單一的獨立文章，包含內部交叉參照。編譯 `article1.tex` 會產生包含於檔案中的交叉參照資料 `article1.aux`.
  * 像是外部檔案 `article1.tex` ，可能由他人撰寫——供你「照原樣」使用，也就是不做任何修改。
* `**latexmkrc**`：包含用來自動重新編譯……的程式碼（Perl） `article1.tex` 因其任何變更——以建立更新的 `article1.aux` 檔案中使用的指令。
  * 我們的 `latexmkrc` 檔案是 [由 John Collins 提供給 Overleaf 的](#code-for-latexmkrc) ([維護者 `latexmk`](https://ctan.org/pkg/latexmk?lang=en)).

### 關於 \externaldocument 命令

該 `xr` 套件提供`\externaldocument` 命令，其一般形式為

```latex
\externaldocument[prefix]{external_file}
```

* **`前綴` （選填）：** 此選填引數可讓你定義一個前綴，會加到從外部文件匯入的所有標籤之前。若多個文件使用相同標籤名稱，這有助於避免衝突。
* **`external_file` （必填）：** 此必填引數指定外部 LaTeX 文件的名稱（不含 `.tex` 副檔名），你要 `xr` 套件會尋找 `.aux` 對應於……的檔案 `external_file` （例如， `external_file.aux`）以擷取標籤。

舉例來說，如果我們的主要 `.tex` 檔案 `summary.tex` 以及外部檔案， `article1.tex` 都包含標籤 `\label{eq:1}` 那麼就會有標籤名稱衝突。可透過撰寫

```latex
\externaldocument[art1-]{article1}
```

在這種情況下，透過編譯 `article1.tex` 所建立的所有標籤都會加上前綴 `art1-`。現在你可以存取 `\label{eq:1}`，其包含於 `article1.tex`，只要寫下 `\ref{art1-eq:1}` 中插入一個 `summary.tex`.

### 專案檔案

#### article1.tex

以下程式碼可透過清單下方的連結在 Overleaf 中開啟。

```latex
\documentclass{article}
\title{這是 \texttt{article1.tex}}
\begin{document}
\section{簡介}
\label{introduction}

這是一個獨立的 \LaTeX{} 文件，包含
我們想在 \texttt{summary.tex} 中使用的參照。

\subsection{數學參照}
\label{mathrefs}
如在第 \ref{introduction} 節所提到，
不同的元素可以在
一個文件中被參照。

\subsection{冪級數}
\label{powers}

\begin{equation}
\label{eq:1}
\sum_{i=0}^{\infty} a_i x^i
\end{equation}

公式 \ref{eq:1} 是一個典型的冪級數。
\end{document}
```

[開啟 `article1.tex` 在 Overleaf 中](https://www.overleaf.com/docs?engine=%5B%5B%3ATemplate%3AEngine%5D%5D}\&snip_name\[]=readme.txt\&snip\[]=A+project+created+from+the+Overleaf+wiki\&snip_name\[]=article1.tex\&main_document=article1.tex\&snip\[]=%5Cdocumentclass%7Barticle%7D%0A%5Ctitle%7BThis+is+%5Ctexttt%7Barticle1.tex%7D%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BIntroduction%7D%0A%5Clabel%7Bintroduction%7D%0A%0AThis+is+a+standalone+%5CLaTeX%7B%7D+document+with%0Areferences+we+want+to+use+in+%5Ctexttt%7Bsummary.tex%7D.%0A%0A%5Csubsection%7BMath+references%7D%0A%5Clabel%7Bmathrefs%7D%0AAs+mentioned+in+section+%5Cref%7Bintroduction%7D%2C+%0Adifferent+elements+can+be+referenced+within%0Aa+document.%0A%0A%5Csubsection%7BPowers+series%7D%0A%5Clabel%7Bpowers%7D%0A%0A%5Cbegin%7Bequation%7D%0A%5Clabel%7Beq%3A1%7D%0A%5Csum_%7Bi%3D0%7D%5E%7B%5Cinfty%7D+a_i+x%5Ei%0A%5Cend%7Bequation%7D%0A%0AEquation+%5Cref%7Beq%3A1%7D+is+a+typical+power+series.%0A%5Cend%7Bdocument)

編譯 `article1.tex` 會產生以下輸出：

![在 Overleaf 上編譯 article1.tex 檔案所產生的輸出](/files/fa3669ac0126c8a79ae85c810932e2a244b08ddd)

#### summary.tex

這是我們的初始 `summary.tex` 檔案 *，在* 我們已指定要參照哪個外部文件。為了簡化， `summary.tex` 不包含任何 `\label` 命令，因為沒有內部交叉參照。所有 `\ref` 命令都參照由……產生的標籤 `\label` 命令所包含的 `article1.tex`.

```latex
\documentclass{article}
\usepackage{xr}
\title{這是 \texttt{summary.tex}}
\begin{document}
在 \texttt{article1.tex} 檔案中，導言是第 \ref{introduction} 節。 在該檔案中，有兩個小節：\ref{mathrefs} 與 \ref{powers}。在第 \ref{powers} 小節中，方程式 \ref{eq:1} 示範了一個冪級數。
\end{document}
```

[在 Overleaf 中開啟這個 *不完整* `summary.tex` 在 Overleaf 中](https://www.overleaf.com/docs?engine=%5B%5B%3ATemplate%3AEngine%5D%5D}\&snip_name\[]=readme.txt\&snip\[]=A+project+created+from+the+Overleaf+wiki\&snip_name\[]=summary.tex\&main_document=summary.tex\&snip\[]=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bxr%7D%0A%5Ctitle%7BThis+is+%5Ctexttt%7Bsummary.tex%7D%7D%0A%5Cbegin%7Bdocument%7D%0AIn+the+file+%5Ctexttt%7Barticle1.tex%7D%2C+the+introduction+is+section+%5Cref%7Bintroduction%7D.++In+that+file%2C+there+are+two+subsections%3A+%5Cref%7Bmathrefs%7D+and+%5Cref%7Bpowers%7D.+In+subsection+%5Cref%7Bpowers%7D%2C+equation+%5Cref%7Beq%3A1%7D+demonstrates+a+power+series.%0A%5Cend%7Bdocument%7D)

如果我們編譯這個版本的 `summary.tex` 它會嘗試從……讀取參照資料 `summary.aux` 但所需資料包含在外部檔案中 `article1.aux` ，但目前尚無法存取。

編譯這個不完整的 `summary.tex` 檔案會產生以下輸出，雙問號表示未定義的參照：

![顯示遺失參照報告的圖片](/files/e53792f61cac7bf0e948b54dc6eea61f68940c7e)

### 指定外部文件

下一步是指定 `article1` 作為我們要參照其標籤的外部文件名稱。將以下行加入……的前言區 `summary.tex`:

```latex
\externaldocument{article1}
```

在此， `article1` 可以替換為任何你想存取其標籤的檔案——你可以使用多個 `\externaldocument` 命令來存取其他外部檔案。

### 建立 latexmkrc 檔案

下一步是建立一個 `latexmkrc` 如下所示的檔案：

* 在你的專案編輯器視窗中，選取 **新檔案** 專案視窗左上角的圖示。
* 選擇 **新檔案** 在……之中 **新增檔案** 彈出對話方塊，並將檔案命名為 `latexmkrc`——注意沒有檔案副檔名：

![在 Overleaf 中建立 latexmkrc 檔案](/files/504961ac66ac3d3b2d6cba469f6f0240b32c23c5)

* 請確保 `latexmkrc` 檔案是建立並儲存在專案檔案區最上層（根層）。也就是說，不要放在檔案樹中的任何資料夾裡。
* 將以下程式碼複製並貼到你的 `latexmkrc` 檔案中使用的指令。

#### latexmkrc 程式碼

Overleaf 感謝 John Collins， [維護者 `latexmk`](https://ctan.org/pkg/latexmk?lang=en)，因為他聯繫我們提供以下 `latexmkrc` 檔案，我們很高興完整刊出——包括非常有幫助的行內註解。

```perl
# 這示範如何將 xr 套件與 latexmk 搭配使用。
# John Collins 2023-03-29
#
# xr 套件（「外部參照系統」）由文件使用
# 來對其他外部的章節、方程式等進行參照
# 文件。
# 本檔案中的定義可讓 latexmk 將 latexmk 套用到
# 當外部文件的 .tex 檔變更時，自動更新該文件，
# 使主文件中的參照保持最新。

# 注意：
#    1. 此版本被設計為將……編譯所產生的檔案放入
#       一個指定的子目錄，以便將
#       可能產生的大量檔案與主文件
#       的目錄分開。
#    2. 但若要像這裡一樣使用 latexmk 的自訂相依機制，
#       子文件編譯產生的 aux 檔必須生成於
#       與對應來源 .tex 檔相同的目錄中。因此，
#       會複製 .aux 檔。
#    3. 假設外部文件將由
#       pdflatex 編譯。當然，可透過變更 '-pdf'
#       傳給所呼叫 latexmk 的選項來改成所需的任何值。
#    4. 理想的實作也會確保外部文件的重新編譯會在以下情況發生：
#       只要它的其他來源
#       檔案有變更。但目前版本尚未這麼做，而且
#       這很可能需要使用 latexmk 內部變數，或是
#       對 latexmk 作額外強化。
#    5. 程式碼使用 copy 和 fileparse 兩個子程序，它們由
#       latexmk 從 Perl 套件 File::Copy 與 File::Basename 載入。
#    6. 它也使用了 latexmk 一些尚未文件化的功能：一個陣列
#       變數 @file_not_found，以及子程序 popd、pushd 和
#       rdb_add_generated。

#--------------------
# 外部文件編譯的可設定選項

# 外部文件編譯輸出檔案的子目錄：
$sub_doc_output = 'output-subdoc';

# 提供給 latexmk 以編譯外部文件的選項：
@sub_doc_options = ();

push @sub_doc_options, '-pdf'; # 使用 pdflatex 來編譯外部文件。
# 如有需要，將 '-pdf' 換成 '-pdfdvi'、'pdfxe' 或 'pdflua'。

#--------------------

# 將 xr 關於缺少檔案的日誌檔訊息模式新增到 latexmk 的
# 清單中。Latexmk 的變數 @file_not_found 尚未文件化。
# 這一行對 4.80 版或更新版本的 latexmk 並非必要。
push @file_not_found, '^No file\\s*(.+)\\s*$';

add_cus_dep( 'tex', 'aux', 0, 'makeexternaldocument' );
sub makeexternaldocument {
    if ( $root_filename ne $_[0] )  {
        my ($base_name, $path) = fileparse( $_[0] );
        pushd $path;
        my $return = system "latexmk",
                            @sub_doc_options,
                            "-aux-directory=$sub_doc_output",
                            "-output-directory=$sub_doc_output",
                            $base_name;
        if ( ($sub_doc_output ne '') && ($sub_doc_output ne '.') ) {
               # 在這種情況下，由 pdflatex 產生的 .aux 檔不在相同的
               # 目錄中。
               # 因此：
               # 1. 實際產生的 aux 檔必須列為由此
               #    規則所產生，如此 latexmk 才能正確處理相依性。
               #    （需克服的問題：如果 $sub_dir_output 與 $aux_dir 相同，
               #    對主文件而言，xr 可能會讀取位於
               #    aux_dir 的 .aux 檔，而不是 latexmk 對這個自訂相依項
               #    所假定會產生的那個檔案；而那個檔案是在與 .tex 來源
               #    檔相同的目錄中。）
               #    使用尚未文件化的 latexmk 子程序 rdb_add_generated
               #    來執行此事：
               # 2. .aux 檔的副本必須位於與 .tex 檔相同的目錄中
               #    以符合 latexmk 對自訂相依項的定義。
             rdb_add_generated( "$sub_doc_output/$base_name.aux" );
             copy "$sub_doc_output/$base_name.aux", ".";
        }
        popd;
        return $return;
   }
}
```

### 開啟示範 xr 的 Overleaf 專案

現在可使用上方與下方提供於檔案清單周圍的連結，在 Overleaf 中開啟以下三檔案專案。請注意， `latexmkrc` 檔案包含 John Collins 提供的程式碼，但為求簡潔，大多數註解已移除。

[在 Overleaf 中開啟此三檔案範例。](/latex/zh-tw/zhi-shi-ku/033-cross-referencing-with-the-xr-package-in-overleaf.md)

**summary.tex**

這是我們的摘要檔案。我們想在這個檔案中使用外部檔案所建立的交叉參照。在這裡，我們想使用由……產生的標籤 `article1.tex`.

```latex
\documentclass[12pt]{article}
\usepackage{xr}

\title{在 Overleaf 上使用 xr 套件}
% 把所有外部文件都放在這裡！
\externaldocument{article1}

\begin{document}

在 \texttt{article1.tex} 檔案中，導言是第 \ref{introduction} 節。 在該檔案中，有兩個小節：\ref{mathrefs} 與 \ref{powers}。在第 \ref{powers} 小節中，方程式 \ref{eq:1} 示範了一個冪級數。

\end{document}
```

**article1.tex**

這個檔案是我們的文章之一。請注意它包含各種 `\label` 用來建立標籤的命令，多虧了 `xr` 套件，我們可以在檔案中使用 `summary.tex`.

```latex
\documentclass{article}
\title{這是 \texttt{article1.tex}}
\begin{document}
\section{簡介}
\label{introduction}

這是一個獨立的 \LaTeX{} 文件，包含
我們想在 \texttt{summary.tex} 中使用的參照。

\subsection{數學參照}
\label{mathrefs}
如在第 \ref{introduction} 節所提到，
不同的元素可以在
一個文件中被參照。

\subsection{冪級數}
\label{powers}

\begin{equation}
\label{eq:1}
\sum_{i=0}^{\infty} a_i x^i
\end{equation}

公式 \ref{eq:1} 是一個典型的冪級數。
\end{document}
```

**latexmkrc**

這個 `latexmkrc` 檔案包含可確保外部檔案被編譯的程式碼。

```latex
$sub_doc_output = 'output-subdoc';

@sub_doc_options = ();

push @sub_doc_options, '-pdf'; # 使用 pdflatex 來編譯外部文件。
# 如有需要，將 '-pdf' 換成 '-pdfdvi'、'pdfxe' 或 'pdflua'。

push @file_not_found, '^No file\\s*(.+)\\s*$';

add_cus_dep( 'tex', 'aux', 0, 'makeexternaldocument' );
sub makeexternaldocument {
    if ( $root_filename ne $_[0] )  {
        my ($base_name, $path) = fileparse( $_[0] );
        pushd $path;
        my $return = system "latexmk",
                            @sub_doc_options,
                            "-aux-directory=$sub_doc_output",
                            "-output-directory=$sub_doc_output",
                            $base_name;
        if ( ($sub_doc_output ne '') && ($sub_doc_output ne '.') ) {

             rdb_add_generated( "$sub_doc_output/$base_name.aux" );
             copy "$sub_doc_output/$base_name.aux", ".";
        }
        popd;
        return $return;
   }
}
```

[在 Overleaf 中開啟此三檔案範例。](/latex/zh-tw/zhi-shi-ku/033-cross-referencing-with-the-xr-package-in-overleaf.md)

下列圖形是排版 `summary.tex`的輸出加註說明的版本，顯示了交叉參照以及外部檔案中的對應標籤 `article1.tex`.

![顯示從外部檔案匯入的參照](/files/b39383b2cfc7ad97ab86f8d9c6355566fc061b4f)

* 如需更多關於交叉參照的細節，請參閱 Overleaf 文章 [交叉參照章節、公式與浮動體](/latex/zh-tw/wen-jian-jie-gou/03-cross-referencing-sections-equations-and-floats.md).

## 關於語法錯誤的說明

對於你的主專案檔，你可以使用 Overleaf 的 [「在第一個錯誤即停止」編譯模式](/latex/zh-tw/zhi-shi-ku/149-using-the-stop-on-first-error-compilation-mode.md) 以確保在偵測到第一個錯誤時編譯立即終止。這有助於隔離並識別程式碼中的錯誤，而不是讓錯誤連鎖擴散，進而使問題更難找到與除錯。

該 *external* 文件會透過……自動編譯 `latexmkrc` 檔案；因此，這些檔案中的任何 LaTeX 語法錯誤都不會顯示在 Overleaf 介面中——除非你也在 Overleaf 中重新編譯它們。這些外部檔案中的錯誤可能會導致交叉參照無法正確顯示在排版後的 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-tw/zhi-shi-ku/033-cross-referencing-with-the-xr-package-in-overleaf.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.
