![在 tcolorbox 中格式化 C 代码](https://linux22.com/image/375707/%E5%9C%A8%20tcolorbox%20%E4%B8%AD%E6%A0%BC%E5%BC%8F%E5%8C%96%20C%20%E4%BB%A3%E7%A0%81.png)
我正在尝试将 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 中没有颜色,因此格式化效果不佳。
接下来,我又尝试了一次,但失败了。请参阅下面的代码片段-
\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}