listings,autoref – Resolving Strange Autoref Countering in lstlisting

autoreflistings

I made a new listtype called mycodes and want to autoref to them. The problem is, when using autoref to a lstlisting-block the number of the listing is wrong!


The code

\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}

The Output

![LaTeX Output


Expected Output

I would like to get the real number of the codeblock as also shown in the subcaption of the lstlistings. So something like:

Codeexample 1.1
Codeexample 1.2
Codeexample 1.3

How to do so?

Best Answer

Use caption and set the position to bottom:

\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}

enter image description here

Related Question