# Create filename with a counter in a command

the code below is not efficient as I would like :

\documentclass{article}

\usepackage{graphicx}

\newcounter{nomfigcpt} % compteur pour compter les figures insérées dans le document
\newcommand{\nomfig}{\jobname\_fig\_\thenomfigcpt.pdf\stepcounter{nomfigcpt}}

\begin{document}

\nomfig

\nomfig

%\includegraphics[scale=1]{\nomfig}

\end{document}


As you can see on the pdf the command

\nomfig

is efficient but when I want to use it in

\includegraphics

it doesn't work instead of the file is in the directory.

I suppose that my solution is too naive and I have tried to find a solution without any success.

I use pdflatex -synctex=0 -shell-escape -interaction=nonstopmode %.tex

Is anyone could help me ?

• \stepcounter is not expandable, which means you can't use it in a file name. You will have to split the \stepcounter{nomfigcpt} part of the command and the file name. Also the \_ need to be only _ in the file name. – Phelype Oleinik Aug 20 '19 at 13:55
• @Phelype Oleinik : Thank you. I have understood the idea. I think that Schrödinger's cat has given the solution. – Benoit Aug 20 '19 at 20:13
• @Schrödinger's cat : thanks a lot for the solution. Unfortunately, the second command [code]\curfig[\code] does not increment the counter. Is there any way to do both get the name as a string and incremet the counter ? – Benoit Aug 20 '19 at 20:21

The mandatory argument to \includegraphics must expand to a string of characters, in order to identify a file name. Instructions such as \stepcounter{...} cannot be used in that argument.

A simple way out is to use a new command:

\newcommand{\numberedimage}[1][]{%
\includegraphics[#1]{\jobname_fig_\arabic{nomfigcpt}}%
\stepcounter{nomfigcpt}%
}


so you can call either form:

\numberedimage

\numberedimage[width=\textwidth]

• This is the perfect and final solution to my problem. Thank you very much. – Benoit Aug 20 '19 at 20:48