How to reference source code listing

I am using the listings package to incorporate listings into my paper.

However I’d like to reference individual parts of the code with a small circular number (such as say the number 1 in white surrounded by a small black filled circle) and then reference this within the main body outside of the listing by reusing the small graphic along with some explanatory text.

I am not sure how to place my code here but essentially it is just code within:

this is some code here...

So in summary a way of referencing an individual part of a listing within the code and using that reference in my main body. In the above example say a small indicator by the ‘some’ and then be able to reference that in my body afterwards.

Apologies if I sound confused. I know what I am trying to do but couldn’t see any way of doing it in the listing documentation.

Solutions Collecting From Web of "How to reference source code listing"

By default the listings package seems to number labels with the line number itself (even if line numbering is hidden!), which it is an elegant option. So, I recommend using the line number as reference instead of adding more noise.

In the code I show three ways of doing it 1) using the line as reference, 2) using a footnote and 3) perhaps what you want which is to a personalized label.


Bla bla


\begin{lstlisting}[escapeinside={(*}{*)}, numbers=right]
/* Hello World program */

    printf("Hello World"); (*\label{code:printf}*)
    double a = b (*\textcolor{red}{\footnote{This is a variable $b$}}*) + c;
    double d = b (*\textcolor{red}{(\refstepcounter{codecounter}\thecodecounter\label{code:b})}*) + c;


We produce the output in line \ref{code:printf}. Or concentrate on \textcolor{red}{(\ref{code:b})}.


We produce the output in line \ref{code:printf}.


The numbers can appear on the right with numbers=right