# Use same reference count for lstlisting and figure/graphics

I have the following code on overleaf:

\begin{lstlisting}[caption={Código inicial para o sistema de arquivos},label={lst:Figura1}]
abstract sig FSObject { }

sig File, Dir extends FSObject { }

sig FileSystem {
root: Dir,
live: set FSObject,
contents: Dir lone-> FSObject,
parent: FSObject ->lone Dir
}{
no root.parent
live in root.*contents
parent = ~contents
}

pred example { }

run example for exactly 1 FileSystem, 4 FSObject
\end{lstlisting}

Ao executar o código da Figura \ref{lst:Figura1} no interpretador Alloy, diversas instâncias são encontradas. A Figura \ref{fig:Figura2} apresenta uma instância selecionada para análise.

\begin{figure}[ht]
\centering
\includegraphics[width=.5\textwidth]{MyFigure2.jpg}
\caption{Contra-exemplo na modelagem}
\label{fig:Figura2}
\end{figure}


which ends up starting a count for Images and listing (code), as seen on the image below, where I highlighted in blue what is wrong for me. I'd like to have a single counter, as if lstlisting had value 1, and the image had value 2.

Is it possible? How do I achieve that?

• I'm using overleaf.com so not quite sure it's a problem with the setup. Maybe some extra config I added? – Vini.g.fer Dec 2 '18 at 13:35

The following is a quick and dirty method. I just redefine the counter to be the same register as the one used for figures. A perhaps better approach could be to patch the \@begindocumenthook to remove the \newcounter{lstlisting} and add everything done by \newcounter except for the register assignment by hand.

\documentclass[]{article}

\usepackage{listings}
\usepackage[]{graphicx}

\makeatletter
\AtBeginDocument{\let\c@lstlisting\c@figure}
\makeatother
%%

\begin{document}
\begin{lstlisting}[caption=foo,label=lst:bar,float]
this listing
\end{lstlisting}
Listing \ref{lst:bar} and figure \ref{fig:bar}

\begin{figure}% >>>
\centering
\includegraphics{example-image-duck}%
\caption
{%
A caption%
\label{fig:bar}%
}%
\end{figure}% <<<
\end{document}


• Awesome!! Your hack worked @Skillmon. Thank you! – Vini.g.fer Dec 2 '18 at 22:32
• You'd also have to watch out, that the order of figures is correct, since a figure could overtake a listing or vice-versa, probably one should also include safety measures for float positioning. – Skillmon likes topanswers.xyz Dec 13 '18 at 8:48