2

I frequently need to put C code into my document, so I defined,

\newcommand{\Ccode}[1]{\lstinputlisting[backgroundcolor=\color{gray!5},caption=\texttt{\lstname},language=C]{C/#1}}

in my document preamble. I have a directory called C, where I have all my C source code, so I just import those code into my document using this,

\Ccode{screen_buffer.c}

Now, in my document, I want to refer to one of my code using \label{} and \ref{} but I don't know where to put the \label{}. So, how do I cross reference my code, if it is possible at all.

EDIT: My document is

\documentclass[11pt]{book}
\title{Computational Physics}
\author{Ayatana}
\usepackage{listings, xcolor}

\newcommand{\Ccode}[1]{
    \lstinputlisting[backgroundcolor=\color{gray!5},
    caption=\texttt{\lstname},language=C]{C/#1}
}
\renewcommand{\lstlistingname}{Code}
\lstset{
    frame=single,
    breaklines=true,
    numbers=left,
    numberstyle=\color{gray}\small\texttt,
    basicstyle=\ttfamily,
    columns=fullflexible,
    showstringspaces=false
    captionpos=b,
}

\begin{document}
The \texttt{Hello World} code in C programming language goes like this,
\Ccode{hello.c}
\end{document}

pdflatex rendered like this, pdftlatex rendering

Now I want to refer to the above code using \ref{}. So, where do I put \label{}?

2
  • Welcome to TeX.SX! Please provide a working document, not just fragments of code. The listings environment has a label key option, as far as I know
    – user31729
    Dec 12, 2015 at 11:17
  • 1
    Typical problem of macros. They can be handy, but can make loss of functionality. You need to extend the macro Ccode to have an optional argument (which takes your label). Or simply define the label to have the same name as the file that is input.
    – Johannes_B
    Dec 12, 2015 at 11:42

1 Answer 1

2

The label is possible with label=.... I suggest to use an optional argument to \Ccode where the label can be specified (and #2 is for the external code file)

\documentclass[11pt]{book}
\title{Computational Physics}
\author{Ayatana}
\usepackage{listings, xcolor}

\newcommand{\Ccode}[2][]{
    \lstinputlisting[backgroundcolor=\color{gray!5},
    caption=\texttt{\lstname},language=C,#1]{#2}
}
\renewcommand{\lstlistingname}{Code}
\lstset{
    frame=single,
    breaklines=true,
    numbers=left,
    numberstyle=\color{gray}\small\texttt,
    basicstyle=\ttfamily,
    columns=fullflexible,
    showstringspaces=false
    captionpos=b,
}

\begin{document}
The \texttt{Hello World} code in C programming language goes like this,
\Ccode[label={myhello}]{hello.c}

In listing \ref{myhello} we see


\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .