# How to number listings by section number? [duplicate]

I want to include several listings in my document with sections. I also want each listing to have labels like Listing 2.1 where 2 is section number and 1 is number of given listing within that section. So far I was able to produce this code:

\documentclass[a4paper]{article}
\usepackage{listings}
\lstset{frame=Trbl,numbers=left}

\begin{document}
\renewcommand{\thelstlisting}{\thesection.\arabic{lstlisting}}

\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}


But this produces the following result:

How can I reset the counter after the beginning of each section?

## marked as duplicate by Werner, Malipivo, Community♦Apr 16 '15 at 5:19

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

## 1 Answer

Solution is to include package chngcntr and to place \counterwithin{lstlisting}{section} after \begin{document}. The complete code is then

\documentclass[a4paper]{article}
\usepackage{listings,chngcntr}
\lstset{frame=Trbl,numbers=left}
\usepackage{amsmath}

\begin{document}
\counterwithin{lstlisting}{section}

\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}


which produces the desired output:

• I am gettng this Package chngcntr Error: lstlisting is not a counter \counterwithin{lstlisting}{section} – jonaprieto Mar 5 '17 at 6:11
• @jonaprieto Strange, my MWE compiles on my computer. I'm using MiKTeX 2.9 and LaTeX Studio 2.12.0 . Did you \usepackage{listings}? – programagor Mar 15 '17 at 19:18
• yes; I was my mistake, I put it before begin document. sorry. – jonaprieto Mar 16 '17 at 12:45