LaTeX文档中的C源代码

10

有人能推荐一个好的模板,在Latex中包含带有行号的C源代码吗?例如,以经典的Hello world程序为例,我想让它看起来像下面这样:

(1)   /* Hello World program */
(2)
(3)   #include<stdio.h>
(4)
(5)   main()
(6)   {
(7)    printf("Hello World");
(8)   }

通常情况下,我总是使用verbatim环境,但我想知道是否有更好、更美观的方法。

非常感谢 Richard


1
请查看tex.stackexchange.com和https://dev59.com/xXRB5IYBdhLWcg3wCjcV,这些网站与编程有关。 - deinst
可能会在TeX和LaTeX stackexchange上得到更好的答案。 - Grzegorz Gierlik
5个回答

15

正如其他人所说,listings包可能会使用以下方式做你想要的事情:

\lstset{
  language=C,                % choose the language of the code
  numbers=left,                   % where to put the line-numbers
  stepnumber=1,                   % the step between two line-numbers.        
  numbersep=5pt,                  % how far the line-numbers are from the code
  backgroundcolor=\color{white},  % choose the background color. You must add \usepackage{color}
  showspaces=false,               % show spaces adding particular underscores
  showstringspaces=false,         % underline spaces within strings
  showtabs=false,                 % show tabs within strings adding particular underscores
  tabsize=2,                      % sets default tabsize to 2 spaces
  captionpos=b,                   % sets the caption-position to bottom
  breaklines=true,                % sets automatic line breaking
  breakatwhitespace=true,         % sets if automatic breaks should only happen at whitespace
  title=\lstname,                 % show the filename of files included with \lstinputlisting;
}

\lstinputlisting{HelloWorld.c}

一个更加强大的替代方案是使用minted宏包,虽然这将比你目前所要求的做得更多,因为它需要使用/安装pygments在您的系统上,以便它可以完全标记您提供的代码。


10

你可能想要看一下 listings。它非常灵活且易于使用。


1

0
使用lgrind软件包来处理latex。它可以将您的代码转换为.tex文件。

-1

CWEB有一个很好的C格式化程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接