2

I'm documenting some C++ code. Each C++ function will have it's own section in my documentation, and I am trying to have each section labelled and each mention of the function linked.

The macros I am currently using are

\usepackage{hyperref}

\newcommand{\cppsection}[1]{\section{#1}\label{#1}}
\newcommand{\cppfcn}[1]{\hyperref[#1]{\texttt{#1}}}

which works for the most part...

...except for if the C++ function has an underscore. For example, \cppsection{my_fcn} doesn't work as it complains about the underscore for the section name, and \cppsection{my\_fcn} doesn't work as it complains about the backslash in the label definition.

This issue is likewise for the \cppfcn macro.

So my question is: Is there a way to define my macros to parse underscores for both the text and the label?

4

You can \detokenize the output:

enter image description here

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{hyperref}

\newcommand{\cppsection}[1]{\section{\protect\detokenize{#1}}\label{#1}}
\newcommand{\cppfcn}[1]{\hyperref[#1]{\texttt{\detokenize{#1}}}}

\begin{document}

\tableofcontents

\cppsection{function} See \cppfcn{procedure}.

\cppsection{procedure} See \cppfcn{fnc_proc}.

\cppsection{fnc_proc} See \cppfcn{function}.

\end{document}
3
  • You're a legend, your MWE works fine. But once I add a \tableofcontents it fails, complaining about the lack of a math environment for the underscore in the test.toc file. Any ideas?
    – kapple
    Oct 21 '20 at 3:33
  • @kapple: You need to \protect certain things that go in the ToC. Answer has been updated.
    – Werner
    Oct 21 '20 at 3:48
  • Works wonders, thanks heaps!
    – kapple
    Oct 21 '20 at 3:55
1

Probably this answer

And try:

\documentclass{book}
\usepackage{fontspec}

\catcode`_=12
\newcommand\Test[1]{%
  \section{#1}%
}
\begin{document}

\Test{test_test}
Text_text
\end{document}
1
  • 1
    Now try some math: $A_b$. You could instead do something like \newcommand\Test{\begingroup\catcode`\_=12 \Testaux} \newcommand\Testaux{\endgroup\section} Oct 21 '20 at 10:44
1
% optional, not necessary:  \usepackage[T1]{fontenc}
%
\usepackage[english]{babel}% or your language
\usepackage{underscore}
\usepackage{hyperref}
. . . 
\cppsection{my_fcn}

Subscripts will still work in math mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.