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



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?


You can \detokenize the output:

enter image description here






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

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

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

  • 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

Probably this answer

And try:



  • 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
% optional, not necessary:  \usepackage[T1]{fontenc}
\usepackage[english]{babel}% or your language
. . . 

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.