子文件“命令已定义”问题

子文件“命令已定义”问题

我遇到了以下问题:使用子文件包、4 个文件、一个子目录和序言中的输入的组合,并且“外部”文件子文件导入子目录中的“内部”文件。我可以编译外部文件,但在单独编译内部文件时,我收到命令已定义错误,根据我对子文件的理解,不应该出现这种情况。

详细来说我有:

  • 主文本
\documentclass{book}
\usepackage{subfiles}
\input{preamble}
\input{sub/preamble}
\begin{document}
\testing
\subfile{sub/main}
\end{document}
  • 序言.tex
\newcommand{\testing}{1, 2, and 3}
  • 子/main.tex
\documentclass[../main]{subfiles}
\begin{document}
\helloWorld
\end{document}
  • sub/序言.tex
\newcommand{\helloWorld}{Hello World}

在最新的 macos 上使用最新的 pdflatex 编译 main.tex 工作正常,但是当我编译 sub/main.tex 时,我收到错误

...
! LaTeX Error: Command \helloWorld already defined.
               Or name \end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              
                                                  
l.1 \newcommand{\helloWorld}{Hello World}
...

我感觉这和 subfiles 使用的 import 包有关系,但是调试了好久也没发现错误,现在我的项目中,我在 sub/preamble.tex 中定义了一个命令,然后在输入 sub/preamble.tex 之前先检查了 main.tex 中这个命令是否未定义。

  • 主文本
\documentclass{book}
\usepackage{subfiles}
\usepackage{ifthen}
\input{preamble}
\ifthenelse{\isundefined\subPreamble}{\input{sub/preamble}}{}
\begin{document}
\testing
\subfile{sub/main}
\end{document}
  • sub/序言.tex
\newcommand{\subPreamble}{}
\newcommand{\helloWorld}{Hello World}

这个解决方案虽然有效,但似乎不正确。有人有更好的解决方案吗?

谢谢,乔恩

答案1

感谢 user202729 和 Ulrike Fischer 指出了名称重叠和 Subfiles 复制带有相对路径的前言的问题。我的解决方案是使用 \subfix 并修改外部 main.tex,如下所示:

\documentclass{book}
\usepackage{subfiles}
\input{\subfix{preamble}}
\input{\subfix{sub/preamble}}
\begin{document}
\testing
\subfile{sub/main}
\end{document}

谢谢你们。

相关内容