[Tex/LaTex] How to force lstlisting caption names and numbers to always appear, even when captions are empty

captionsenvironmentslistings

I noticed lstlisting environment seems to supress the caption name and number when no caption is specified.

See the code below:

\documentclass{article}
\usepackage{listings}
\lstset{language=C}
\begin{document}
The listing below will have no caption.
\begin{lstlisting}
int main(int argc, char *argv[])
{
    return 0;
}
\end{lstlisting}
Now this code will show the caption. 
\begin{lstlisting}
int main(int argc, char *argv[])
{
    return 0;
}
\end{lstlisting}
\end{document}

The only solution I found was to set the caption to be an empty space and to get rid of the separator, but this solution does not look very nice:

\documentclass{article}
\usepackage{listings}
\lstset{language=C}
\usepackage{caption}
\captionsetup{labelsep=none}
\begin{document}
This is not an elegant solution, but works:
\begin{lstlisting}
int main(int argc, char *argv[])
{
    return 0;
}
\end{lstlisting}
\end{document}

Any ideas?

Best Answer

Define a default caption (I used \relax) and setup a caption format that checks whether the given caption is different. The trick is knowing that the caption text is stored in \lst@caption.

\documentclass{article}
\usepackage{listings,caption}

\lstset{language=C,caption=\relax}

\makeatletter
%% define a caption format; if the caption
%% is the default (\relax), the separator is
%% not printed; as long as no caption text
%% starts with \relax, this will work
\DeclareCaptionFormat{alsoempty}{%
  #1\if\relax\expandafter\noexpand\lst@caption\else#2#3\fi}
\makeatother
%% set this format as the default for lstlisting
\captionsetup[lstlisting]{format=alsoempty}

\begin{document}

The listing below will have no caption.
\begin{lstlisting}
int main(int argc, char *argv[])
{
    return 0;
}
\end{lstlisting}
Now this code will show the caption. 
\begin{lstlisting}[caption=This is the caption]
int main(int argc, char *argv[])
{
    return 0;
}
\end{lstlisting}
\end{document}

enter image description here