[Tex/LaTex] Listings numbering in Appendix

listingsnumbering

Currently, I have an issue that in my thesis the numbering of listings in the appendix is not as desired. I currently only get Listing 1 as the numbering of the first listing in the first Appendix, instead of Listing A.1. For figures and tables, I already achieve the desired behavior, that is, the figures and tables get, for instance, the following numbering: Figure A.1.

I just discovered that at the appendix I use the following Latex commands to, obviously, control the behavior of figure and table numbering:

\renewcommand{\thesection}{\Alph{section}}
\renewcommand\thetable{\Alph{section}.\arabic{table}}
\renewcommand\thefigure{\Alph{section}.\arabic{figure}}

What do I have to add to get this to work for listings in the appendix?

Best Answer

The \counterwithin command from chngcntr package does the correct setup without explicit \renewcommand statements of \the.... macros.

The only macro that has to be redefined is \thesection in order to use \Alph{...}.

\documentclass{article}

\usepackage{listings}
\usepackage{chngcntr}

\renewcommand{\thesection}{\Alph{section}}
\counterwithin{figure}{section}
\counterwithin{table}{section}
\AtBeginDocument{%
  \counterwithin{lstlisting}{section}
}



\begin{document}

\section{Foo}

\begin{figure}
\caption{Foo}
\end{figure}

\begin{table}
\caption{Foo}
\end{table}

\begin{lstlisting}[language=C,caption={Foo listing}]

#include<stdio.h>

int main(int argc,char **argv)
{
  printf("Hello World!\n");
  return(0);
}
\end{lstlisting}


\end{document}