Graphics, Figures & TablesCaptions and labels with section numbers

Information and discussion about graphics, figures & tables in LaTeX documents.
Post Reply
Thuleman
Posts: 6
Joined: Tue Oct 12, 2010 12:11 pm

Captions and labels with section numbers

Post by Thuleman »

Hi.

If I have 2 sections and 1 subsection, with 4 listings in each, then I would like the caption and references to do the following: (same with tables and figures)

Code: Select all

Section 1:
Listing 1.1
Listing 1.2
Listing 1.3
Listing 1.4
Section 2:
Listing 2.1
Listing 2.2
Listing 2.3
Listing 2.4
Subsection 2.1:
Listing 2.1.1 (label={listing211})
Listing 2.1.2
Listing 2.1.3
Listing 2.1.4

And when I make a \ref{listing211}
I would like to it to appear as 2.1.1
I create my listings like this:

Code: Select all

\lstinputlisting[firstline=34,lastline=36,firstnumber=34,caption={TCP variabler},
label={lst:variabler}]{server.cpp}

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p

gmedina
Posts: 2313
Joined: Wed Jul 11, 2007 11:45 pm

Captions and labels with section numbers

Post by gmedina »

Hi,

use the chngcntr package. An example:

Code: Select all

\documentclass{article}
\usepackage{listings}
\usepackage{chngcntr}

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

\section{Test section}
\begin{lstlisting}[caption={test},label={test1}]
  ...some code...
\end{lstlisting}
\ref{test1}

\subsection{Test subsection}

{
\counterwithin{lstlisting}{subsection}
\begin{lstlisting}[caption={test},label={test2}]
  ...some code...
\end{lstlisting}
}
\ref{test2}

\section{test}
\begin{lstlisting}[caption={test},label={test3}]
  ...some code...
\end{lstlisting}
\ref{test3}

\end{document}
1,1,2,3,5,8,13,21,34,55,89,144,233,...
Thuleman
Posts: 6
Joined: Tue Oct 12, 2010 12:11 pm

Re: Captions and labels with section numbers

Post by Thuleman »

Hey I have been away for a long time. Very sorry for the late answer.
Thank you very much for the answer, however I still have a problem.

\begin{section}
lstlisting... This will have 1.1
\begin{subsection}
lstlisting... This will have 1.1.2 -- I would like it to have 1.1.1

never mind, I use \setcounter{lstlisting}{0}
Post Reply