引用不適用於 \lstinputlisting

引用不適用於 \lstinputlisting

我可能做錯了什麼,但無法意識到是什麼...

我想為一段程式碼設定一個標籤:

\lstinputlisting[language=Python, label={lst:control_os_call}, firstline=231, lastline=257]{./code/server.py}

所以,我只是嘗試使用 \ref 鏈接它

\ref{lst:control_os_call}

但我總是收到標籤遺失錯誤(僅適用於 上的標籤\lstinputlisting)。那麼...我應該導入任何特定的包來引用這些類型的標籤還是我做錯了什麼?

多謝 :)

答案1

您需要添加一個,caption僅此而已

\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{server.py}
This is some python code
\end{filecontents*}

\usepackage{listings}
\lstset{basicstyle=\ttfamily}

\begin{document}
\lstinputlisting[language=Python,caption={some python code}, label={lst:control_os_call}, firstline=1, lastline=257]{server.py}

Here is the code~\ref{lst:control_os_call}
\end{document}

在此輸入影像描述

相關內容