Listing of a file with underscores in its name/path

I am writing a report with LaTeX and I need to list some source code. One of the files has some underscores in its path/name. When compiling the following line :

\lstinputlisting[label=source_code,caption=test_file.c]{abcd/test_file.c}


I get the following error :

! Package Listings Error: File abcd/test\unhbox \voidb@x \penalty \@M \hskip \ z@skip \unhbox \voidb@x \kern .06em\vbox {\hrule width.3em}\discretionary {-}{} {}\penalty \@M \hskip \z@skip file(.c)' not found.

The underscore is obviously not handled correctly, but I have not been able to find how to correct this so far (tried escaping it with "\_"). Does anyone have any idea on how to solve this?

Test code (works in minimal version, stopped working with "underscore" package) :

% Declarations
\documentclass[a4paper, 11pt,twoside]{article}
\usepackage[utf8x]{inputenc}
\usepackage[french]{babel}
%\usepackage{underscore}

% Code listing
\usepackage{listings}

% Begin document
\begin{document}
\pagestyle{empty}

Listing of test\_file.c :
\lstinputlisting{abcd/test_file.c}

\end{document}


The "underscore" package can help you when you have a lot of underscores to escape in your text, but you have to be careful with file names, cite or ref tags :

The skips and penalties ruin any kerning with the underscore character (when a character is used). However, there doesn’t seem to be much, if any, such kerning in the EC fonts, and there is never any kerning with a rule. You must avoid “_” in file names and in cite or ref tags, or you must use the babel package, with its active-character controls, or you must give the [strings] option, which attempts to redefine several commands (and may not work perfectly). Even without the [strings] option or babel, you can use occasional underscores like: “\include{file\string_name}”.

(Source)

-

migrated from stackoverflow.comNov 17 '11 at 19:57

This question came from our site for professional and enthusiast programmers.

Escape the underscore in the caption argument, but not in the mandatory argument:
lstinputlisting[label=source_code,caption=test\_file.c]{abcd/test_file.c}

OK, fixed. Only escape the caption` argument. –  Kerrek SB Nov 17 '11 at 17:40