2

I'm writing a document in which I have some figures, tables and source code (lstlistings), all with numbered captions e.g. Figure 3.2.1 Caption

All are working properly except in subsections the a \label{lst:code} that shows in the document as Code 3.2.1, where 3 corresponds to the chapter, 2 to the section and 1 to a continuous number of listings within the section, the corresponding \ref{lst:code} would Show as 3.2.2 where the second 2 corresponds to the subsection instead.

All other references work normally. Even if I set the numbering to subsection (with 4 numbers instead 3) the number of the reference (lstlisting) stays with 3 numbers.

Can I somehow manitulate how \ref{} is set for the lstlistings?

Thanks for your help.

\documentclass[a4paper,11pt]{report}
\usepackage[ngerman]{babel}
\usepackage{listingsutf8}
\usepackage{chngcntr}

\begin{document}
\counterwithin{lstlisting}{section}
\lstset{
    showstringspaces=false,
    extendedchars=true,
    inputencoding=utf8,
}
\chapter{Chapter}
\chapter{Chapter}
\chapter{Chapter}
\chapter{Chapter}
\section{section}
\section{section}
\section{section}
\subsection{Program.cs}
\subsection{Program.cs}

Code \ref{lst:code}

\lstset{caption=Code}\label{lst:code}
\begin{lstlisting}
static void Main() {
Application.Run(new Form());
}
\end{lstlisting}

\end{document}

This Returns:

  • Chapter 4

  • 4.3 Section

  • 4.3.2 Subsection

  • 4.3.1 the number of the Codecaption

  • 4.3.2 the number of the Reference but this should be 4.3.1

7
  • You are doing something wrong but as you are not showing what you are doing it is difficult to say what exactly. Make a complete example that demonstrates your issue. Oct 28, 2016 at 12:56
  • presumably you have \label in the wrong place (eg before the \caption) but as you have shown no example that can only be a guess. Oct 28, 2016 at 12:56
  • I won't debug your large code on overleaf. Oct 28, 2016 at 13:09
  • this question is archived forever but your link is not stable even if people agree to follow it. Please make a small example and add it to the question. Oct 28, 2016 at 13:19
  • Added some sample code Oct 28, 2016 at 13:34

1 Answer 1

2

Instead of

\lstset{caption=Code}\label{lst:code}

you need to supply the \label using the label key-value:

\lstset{caption=Code,label=lst:code}

See the top of p 18 in the current documentation for the listings package.

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .