GeneralWhat difference is there between caption and title in lstlisting in latex?

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
goahead97
Posts: 4
Joined: Thu Sep 14, 2023 1:00 pm

What difference is there between caption and title in lstlisting in latex?

Post by goahead97 »

What difference is there between caption and title in lstlisting in latex?
I can see the title on the output pdf. I do not see the label anywhere though. What is the lstlisting label used for?
Thanks

Recommended reading 2024:

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

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

kaiserkarl13
Posts: 707
Joined: Tue Mar 25, 2008 5:02 pm

What difference is there between caption and title in lstlisting in latex?

Post by kaiserkarl13 »

According to the documentation (which you should read!), the "title" field is the entire title of the code sample without a number. The caption is the same thing, except it says "Listing 1: [caption contents]" or similar for second, third, etc. listings. If you specify both, whichever is specified last "wins."

The "label" is how you refer to the caption number in the text (as "\label" won't work inside a verbatim environment). Observe:

Code: Select all

\documentclass{article}
\usepackage{listings}
\begin{document}
%\begin{lstlisting}[title={this is the title},label={hello}]
\begin{lstlisting}[caption={this is a caption},label={hello}]
This is code
# Commented
# etc.
if ( 5 > 3 ) print "hello"
\end{lstlisting}

The listing above is Code sample~\ref{hello}.
\end{document}
If you switch the line that specifies a title with the one that specifies the caption, then re-run LaTeX a couple of times, the "\ref{hello}" part won't work, as there will be no number to refer to.
Post Reply