\begin{lstlisting}
我在报告中用和包含了 MATLAB 代码\end{lstlisting}
,但在同一份报告中,我需要包含 C++ 代码。我希望它能够识别语言并用颜色突出显示等等。我该怎么做?
更新:我现在可以编写 C++ 代码,但我不知道为什么它没有突出显示字符串。
\documentclass[a4paper,11pt]{article}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{commentgreen}{rgb}{.133,.545,.133}
\definecolor{mauve}{rgb}{0.224, 0.176, 0.255}
\lstdefinestyle{defaultStyle}
{
basicstyle=\footnotesize,
tabsize=2,
captionpos=b,
% frame=lines,
breaklines=true,
keepspaces=true
upquote=true,
}
% define C++ style
\lstdefinestyle{cpp}
{
style=defaultStyle,
% language related
language=C++,
keywordstyle=\color{blue},
commentstyle=\color{commentgreen},
stringstyle=\color{mauve},
showstringspaces=false,
%otherkeywords={\#include}, % do not uncomment!
% numbers=left,
numberstyle=\tiny
}
\begin{document}
\begin{lstlisting}[language=C++,style=cpp]
// (1) Defining the path and Loading the Classifier (C format)
char *CascadeFile = "MyCascade/Cascade.xml";
cascade = ( CvHaarClassifierCascade* )cvLoad( CascadeFile);
// (2) Defining the path and Loading the Classifier in (C++ format)
string RootCascade = "MyCascade/";
string Extension = ".xml";
string filename = RootCascade + "Cascade" + Extension;
cascade = ( CvHaarClassifierCascade* )cvLoad( filename.c_str());
\end{lstlisting}
\end{document}
这是输出:
答案1
您可以定义 listings 包的样式
% define general style
\lstdefinestyle{defaultStyle}
{
basicstyle=\footnotesize,
tabsize=2,
captionpos=b,
frame=lines,
breaklines=true,
keepspaces=true
}
% define C++ style
\lstdefinestyle{cppStyle}
{
style=defaultStyle,
% language related
language=C++,
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
showstringspaces=false,
%otherkeywords={\#include}, % do not uncomment!
% numbering
numbers=left,
numberstyle=\tiny
}
style
在 latex 文档中,可以使用关键字指定样式
\begin{lstlisting}[style=cppStyle,caption={Code Numbered},label=lst:numbered]
/* your code here */
\end{lstlisting}