Latex中插入C语言代码

Latex是一个文本排版的语言,能排版出各种我们想要的效果。而且用代码排版的优点是易于修改板式,因此在文本内容的排版时,Latex应用十分广泛。

当我们需要在Latex中插入代码时,就需要用到 usepackage{listings} 宏包。例如插入一个简单的C语言代码

#include <stdio.h>
int main(int argc, char ** argv)
{
    printf("Hello, world!
");
    return 0;
}

要将上面 Hello,world! 这段C语言代码用Latex实现排版的效果,Latex的脚本如下

documentclass{article}
usepackage{listings}
usepackage{xcolor}      %代码着色宏包
usepackage{CJK}         %显示中文宏包


lstset{
    basicstyle=	t,
    %行号
    numbers=left,
    rulesepcolor=color{red!20!green!20!blue!20},
    escapeinside=``,
    xleftmargin=2em,xrightmargin=2em, aboveskip=1em,
    %背景框
    framexleftmargin=1.5mm,
    frame=shadowbox,
    %背景色
    backgroundcolor=color[RGB]{245,245,244},
    %样式
    keywordstyle=color{blue}fseries,
    identifierstyle=f,
    numberstyle=color[RGB]{0,192,192},
    commentstyle=itcolor[RGB]{96,96,96},
    stringstyle=
mfamilyslshapecolor[RGB]{128,0,0},
    %显示空格
    showstringspaces=false
}

begin{document}
begin{CJK*}{GBK}{song}
lstset{language=C}
begin{lstlisting}        %插入要显示的代码
#include <stdio.h>
int main(int argc, char ** argv)
{
    /*`打印`Hello,world*/
    printf("Hello, world!
");

    return 0;
}

end{lstlisting}
end{CJK*}
end{document}

上面的Latex脚本可以显示出C语言中的注释(包括中文注释),代码着色,并添加了代码行号。效果如下

 参考:

[1] https://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings

[2] Latex论坛,http://tex.stackexchange.com/

[3] Latex Beginning's Guide pdf  提取码: ac4n

原文地址:https://www.cnblogs.com/abc36725612/p/5936682.html