Latex中插入C語言代碼


Latex是一個文本排版的語言,能排版出各種我們想要的效果。而且用代碼排版的優點是易於修改板式,因此在文本內容的排版時,Latex應用十分廣泛。

當我們需要在Latex中插入代碼時,就需要用到 \usepackage{listings} 宏包。例如插入一個簡單的C語言代碼

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

要將上面 Hello,world! 這段C語言代碼用Latex實現排版的效果,Latex的腳本如下

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}      %代碼着色宏包
\usepackage{CJK}         %顯示中文宏包


\lstset{
    basicstyle=\tt,
    %行號
    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}\bfseries,
    identifierstyle=\bf,
    numberstyle=\color[RGB]{0,192,192},
    commentstyle=\it\color[RGB]{96,96,96},
    stringstyle=\rmfamily\slshape\color[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!\n");

    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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM