在 tcolorbox 中格式化 C 代码

在 tcolorbox 中格式化 C 代码

我正在尝试将 C 代码放入其中tcolorbox。请参阅下面的代码片段-

\documentclass{standalone}

% for code formatting
\usepackage[formats]{listings}
\usepackage{filecontents}

\usepackage{tcolorbox}

\begin{filecontents*}{code.c}
#define DATA_TYPE_BYTES 4

// receive data
unsigned char* byte_ptr = 
    static_cast<unsigned char*>(msg.data());

// deserialize 
int width;
std::memcpy(&width, byte_ptr, DATA_TYPE_BYTES);
byte_ptr += DATA_TYPE_BYTES;
\end{filecontents*}

\begin{document}
\begin{tcolorbox}[title=Deserialization, hbox]
    %\lstinputlisting[format=C]{code.c} %isn't working
    \lstinputlisting{code.c}
\end{tcolorbox}
\end{document}

上述代码产生以下输出-

生成的 PDF 的屏幕截图

请注意,由于生成的 PDF 中没有颜色,因此格式化效果不佳。

接下来,我又尝试了一次,但失败了。请参阅下面的代码片段-

\documentclass{standalone}
\usepackage{tcolorbox}
\usepackage{listings}

\begin{document}
\begin{tcolorbox}[title=Deserialization, hbox]
    \lstset{language=C++,
        basicstyle=\ttfamily,
        keywordstyle=\color{blue}\ttfamily,
        stringstyle=\color{red}\ttfamily,
        commentstyle=\color{green}\ttfamily,
        morecomment=[l][\color{magenta}]{\#}
    }
\begin{lstlisting}
#define DATA_TYPE_BYTES 4

// receive data
unsigned char* byte_ptr = 
    static_cast<unsigned char*>(msg.data());

// deserialize 
int width;
std::memcpy(&width, byte_ptr, DATA_TYPE_BYTES);
byte_ptr += DATA_TYPE_BYTES;
\end{lstlisting}
\end{tcolorbox}
\end{document}

上述代码无法编译并引发以下错误-

! Illegal parameter number in definition of \lst@insertargs.
<to be read again>
}
l.26 \end{tcolorbox}
You meant to type ## instead of #, right?
Or maybe a } was forgotten somewhere earlier, and things
are all screwed up? I'm going to assume that you meant ##.
LaTeX Font Info: External font `cmex10' loaded for size
(Font) <7> on input line 26.

似乎tcolorbox与不兼容listings。嗯,我想知道如何在里面格式化 C 代码tcolorbox

答案1

tcblisting手动的

\documentclass{standalone}
\usepackage{tcolorbox}
\tcbuselibrary{listings}

\begin{document}

\begin{tcblisting}{
    title=Deserialization,
    hbox,
    listing only,
    listing options={
      language=C++,
      basicstyle=\ttfamily,
      keywordstyle=\color{blue}\ttfamily,
      stringstyle=\color{red}\ttfamily,
      commentstyle=\color{green}\ttfamily,
      morecomment={[l][\color{magenta}]{\#}},
    }
  }
#define DATA_TYPE_BYTES 4

// receive data
unsigned char* byte_ptr = 
    static_cast<unsigned char*>(msg.data());

// deserialize 
int width;
std::memcpy(&width, byte_ptr, DATA_TYPE_BYTES);
byte_ptr += DATA_TYPE_BYTES;
\end{tcblisting}

\end{document}

在此处输入图片描述

相关内容