This may or may not be desirable for your uses, because it doesn't physically alter your code files. (It leaves the \label
s in the code rather than replacing them with the numbers.) But several ways to do this exist using the listings
package's escape to LaTeX features. Other code pretty-printing packages have similar features, but I show an example with listings
because it is the most ubiquitous.
You can use Eq.~\ref{eqn:foo}
directly in the comments, and tell the listings package to escape to LaTeX code between a set of arbitrary delimiters (as shown in the first example, with |
), or to treat all comment lines as escaped LaTeX code, as in the second example.
Here is the general idea:
\documentclass{article}
\usepackage{listings}
\lstset{language=c}
\begin{document}
My code implements
\begin{equation}\label{eq:energy}
e = mc^2,
\end{equation}
which describes the relationship between mass and energy.
The code is displayed in Listing~\ref{lst:func}.
\begin{lstlisting}[
caption={Test function.},
label={lst:func},
escapechar=|,% <-- for escaping to LaTeX inside comments
]
double NucEnergy(double mass){
/* here I have |\itshape Eq.~\ref{eq:energy}| of the text */
< ... code omitted ... >
}
\end{lstlisting}
Another option, where all comment lines are parsed as \LaTeX\ input:
\begin{lstlisting}[
caption={Another test function.},
label={lst:func2},
texcl=true,%<-- to treat all comment lines as escaped LaTeX
]
double NucEnergy(double mass){
// here I have Eq.~\ref{eq:energy} of the text
< ... code omitted ... >
}
\end{lstlisting}
\end{document}

Notice how, in the first example, we are completely in charge of the text style (note \itshape
), while in the second example, the default comment style is automatically used.
\label{foo}
to an equation, then\ref{foo}
will print the number assigned to it. – egreg Jul 18 '14 at 22:08\ref{eqn:myequation}
? Sorry but I'm not following this. Please help us to help you and add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with\documentclass{...}
and ending with\end{document}
. – cfr Jul 18 '14 at 22:08\label
-\ref
mechanism is that you never need to know the actual number, but just the label. The actual number may change with the text, the labels won't. – egreg Jul 18 '14 at 22:11/* this implements equation 5 */
so basically either get TeX to write the source file or perl etc to insert the number from the aux file. – David Carlisle Jul 18 '14 at 22:27.aux
file knows the numbers attached to labels. If you use the labels in your code you can write aperl
(orsed
orawk
) script to replace the label in the code. Better put that in a makefile and recompile the source to make sure nothing's broken. – Ethan Bolker Jul 19 '14 at 0:32