LaTeX forum ⇒ 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.
goahead97
Posts: 4
Joined: Thu Sep 14, 2023 1:00 pm

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

Postby goahead97 » Thu Sep 28, 2023 1:07 pm

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 2021:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
LaTeX Beginner's Guide LaTeX Cookbook LaTeX TikZ graphics
kaiserkarl13
Posts: 706
Joined: Tue Mar 25, 2008 5:02 pm

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

Postby kaiserkarl13 » Sat Sep 30, 2023 3:24 am

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:
\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.


Return to “General”

Who is online

Users browsing this forum: No registered users and 19 guests