我正在编写一个程序(用C语言编写,但我想这不是很重要),它与LaTeX中的一小部分纪录片材料有关。我希望文档材料包含来自我的原始代码的代码片段。
为了包含源代码并使其保持最新,我在我的文档中执行以下操作:
\lstinputlisting[firstline=200, lastline=210]{../src/source.c)
这会自动将第200到210行(其中包含一个函数)从../src/source.c
加载到我的文档中。
但是,如果我在第200行之前添加一些行,这意味着第200行“向下游荡了一些行”,所以我必须调整它以获得我的原始函数。
所以我的问题是:有没有人知道如何动态地告诉lstinputlisting
(或任何适当的替代品)来告诉我们应该走哪一行?
我想象如下所示:我在C源代码中添加了lstinputlisting
可以识别的特殊注释,例如
/// lstinputlisting "myfunc" BEGIN
int myFunction(int x){
return x+2;
}
/// lstinputlisting "myfunc" END
然后,lstlisting
扫描文件,只包含BEGIN
和END
之间的行。
发布于 2011-05-07 04:02:09
我在你的帖子后几个月回复,但我下面描述的lstlistings的功能已经在那个包中存在了几年了。
要查找的关键字是选项linerange
,为了方便起见,还需要查找rangeprefix
和rangesuffix
。
下面是一个完整的示例。
\documentclass{article}
\usepackage{fullpage,times,listings}
\lstloadlanguages{C++}
\lstset{language=C++,keywordstyle=\bfseries,commentstyle=\itshape,
rangeprefix=//----------------,rangesuffix=----------------,
includerangemarker=false,columns=spaceflexible}
\begin{document}
We first show the main function.
\lstinputlisting[linerange=main0-main1]{code.cpp}
Then we show the implementation.
\lstinputlisting[linerange=fact0-fact1]{code.cpp}
\end{document}
然后在code.cpp中保存以下内容:
#include <cassert>
//----------------fact0----------------
// A recursive implementation of factorial
int factorial(int i)
{
if(i)
return i * factorial(i-1);
else
return 1;
}
//----------------fact1----------------
//----------------main0----------------
// Test the implementation.
int main()
{
assert(factorial(5) == 120);
}
//----------------main1----------------
这是一个很好的解决方案,因为用户不可避免地要编辑代码,然后在整个TeX文件中更新行号变得单调乏味。使用符号解决了这个问题,但它也在代码本身中留下了痕迹,即如果行数发生变化,或者如果宽度变化太多,则需要确认排版输出看起来仍然合理。
最后,编辑代码后,仅当在标记的块中插入/删除时,才需要重新排版latex文件。
发布于 2010-10-12 22:32:07
在C中使用#include
不是更容易吗?
这不是完美的解决方案,但已经足够好了。
下面是一个例子(无法编译,我上次用C
写的东西是5年前写的):
主C
程序:
#include <stdio.h>
//function included from separate file -- will be included in LaTeX too
#include "fun_x.c"
int main()
{
int d = 0;
printf("%d", fun_x(d));
//code included from separate file -- will be included in LaTeX too
#include "calc.c"
return 0;
}
fun_x.c
文件:
int fun_x(int c)
{
c++;
return c;
}
calc.c
文件:
d = 99;
d = fun_x(d);
LaTeX来源:
\begin{document}
...
\lstinputlisting{../src/fun_x.c)
...
\lstinputlisting{../src/calc.c)
...
\end{document}
发布于 2010-10-12 22:33:47
我能想到的唯一合理的实现方法是创建一个makefile,并让它负责生成正确的输出。
假设sourcefile.c在./src中,LaTeX文件在./tex中,那么./tex/Makefile可能如下所示:
doc.tex: sourcefile.grep
<command to compile doc.tex>
sourcefile.grep:
<command to grep/whatever to dump from
../src/sourcefile.c to ./tex/sourcefile.grep>
然后doc.tex中的lstlistings将指向./src/sourefile.grep
https://stackoverflow.com/questions/3915709
复制相似问题