我创建了一个名为我的代码并希望自动引用它们。问题是,当使用自动引用到列表块时,列表的编号是错误的!
代码
\documentclass[]{article}
\usepackage[german]{babel}
\usepackage[]{hyperref}
\usepackage{listings}
\lstset{frame=tb}
\usepackage{tocloft}
\newlistof{mycodes}{cod}{}
\newcommand{\mycodes}[2][]{
\refstepcounter{mycodes}
\par\noindent Code \thesection.\themycodes: #2\\
}
\addto\extrasgerman{\def\lstlistingautorefname{Codeexample}}
\begin{document}
\section{Kapitel 1}
\subsection{Unterkapitel 1.1}
\begin{lstlisting}[label=cod:Fun1_1]
void Function()
\end{lstlisting}
\mycodes{Example of Code 1}
\begin{lstlisting}[label=cod:Fun1_2]
void Function()
\end{lstlisting}
\mycodes{Example of Code 2}
\begin{lstlisting}[label=cod:Fun1_3]
void Function()
\end{lstlisting}
\mycodes{Example of Code 3}
\autoref{cod:Fun1_1}\\
\autoref{cod:Fun1_2}\\
\autoref{cod:Fun1_3}\\
\end{document}
输出
预期输出
我想获取代码块的实际编号,如列表的子标题中所示。因此,类似于:
Codeexample 1.1
Codeexample 1.2
Codeexample 1.3
如何做?
答案1
使用标题并将位置设置为底部:
\documentclass[]{article}
\usepackage[german]{babel}
\usepackage[]{hyperref}
\usepackage{listings}
\lstset{frame=tb,captionpos=b}
\renewcommand\lstlistingname{Code}
\AtBeginDocument{\renewcommand\thelstlisting{\thesection.\arabic{lstlisting}}}
\addto\extrasgerman{\def\lstlistingautorefname{Codeexample}}
\begin{document}
\section{Kapitel 1}
\subsection{Unterkapitel 1.1}
\begin{lstlisting}[caption=Example of Code 1,label=cod:Fun1_1]
void Function()
\end{lstlisting}
\begin{lstlisting}[caption=Example of Code 2,label=cod:Fun1_2]
void Function()
\end{lstlisting}
\begin{lstlisting}[caption=Example of Code 3,label=cod:Fun1_3]
void Function()
\end{lstlisting}
\autoref{cod:Fun1_1}\\
\autoref{cod:Fun1_2}\\
\autoref{cod:Fun1_3}
\end{document}