How to reference a label within a newcommand in LATEX?

邮差的信 提交于 2019-12-11 18:10:31

问题


I have created a newcommand \figc to create figures quickly for my document. However, I had trouble referencing it. The document is being compiled successfully but is being shown as Figure (??).

\newcommand{\figc}[3]{    
\begin{figure}[H]
    \centering
    \includegraphics[width={#3}]{figures/{#1}.jpg}
    \caption{{#2}}
    \label{fig:{#1}}
\end{figure}
    fig:{#1}}    ----> However, this part is displayed correctly in the PDF as fig:samplefig


Here is a sample text to reference (Figure \ref{fig:samplefig}).
\figc{samplefig}{Sample Figure}{3in}

回答1:


Don't use fig:{#1} in your \label, but instead use fig:#1:

\documentclass{article}

\usepackage{float,graphicx}

\newcommand{\figc}[3]{%
  \begin{figure}[H]
    \centering
    \includegraphics[width=#3]{#1.jpg}
    \caption{#2}
    \label{fig:#1}
  \end{figure}
  fig:#1% Set the reference as well
}

\begin{document}

Here is a sample text to reference (Figure \ref{fig:example-image}).

\figc{example-image}{Sample Figure}{3in}

\end{document}

There's a difference between what is set in a document, and its internal representation. That's why \label{fig:{abc}} is different from \label{fig:abc}, and therefore can provide an undefined reference.



来源:https://stackoverflow.com/questions/49268698/how-to-reference-a-label-within-a-newcommand-in-latex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!