Given the following MWE, where the argument for the code function contains an underscore:
\documentclass [11pt,oneside,onecolumn]{article}
\usepackage{listings}
\usepackage{filecontents}
\begin{filecontents*}{hello_world.c}
#include <stdio.h>
int main(void) {
printf("Hello World!\n");
// return 0;
}
\end{filecontents*}
\makeatletter
\def\code{\@ifnextchar[{\@with}{\@without}}
\def\@with[#1]#2{
}
\def\@without#1{
\section{#1}
\lstinputlisting[]{#1}
}
\makeatother
\begin{document}
\code{hello_world.c}
\end{document}
The same argument #1 is used in two different functions: section, which requires the underscore to be escaped, and lstinputlisting, which requires the underscore not to be escaped.
If the user escapes the filename, compilation fails because of section. If the user doesn't escape the filename, listings cannot find the filename.
How to solve the issue?
makeatletterandmakeatother, which I just saw in your answer. Putting everything in a single file without those commands was causing aUse of \@ doesn't match its definition.error, which is why I didn't use a single file. I was doing my best to ease your job. Sorry about that. – Roberto Aloi Jul 27 '12 at 16:14\@ifnextchar. – egreg Jul 27 '12 at 20:37