6

我正在编写一个程序(用 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扫描文件并仅包含 theBEGINENDthings 之间的行。

4

4 回答 4

15

我在您的帖子发布几个月后才回复,但我在下面描述的 lstlistings 功能已经在该软件包中使用了好几年。

要查找的关键字是 option linerange,以及,为方便起见,rangeprefixand 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 文件中更新行号变得很乏味。使用符号解决了这个问题,但它也在代码本身中留下了痕迹,如果行数发生变化,或者宽度变化太大,则需要确认排版输出看起来仍然合理。

最后,在编辑代码后,只有在标记的块中插入/删除时,才需要再次排版乳胶文件。

于 2011-05-06T20:02:09.347 回答
1

#include在 C中使用会不会更容易?

它并不完美,但足够好,解决方案。

这是一个示例(无法编译,我上次写的东西是在C5 年前):

主程序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);

乳胶来源:

\begin{document}
...

\lstinputlisting{../src/fun_x.c)

...

\lstinputlisting{../src/calc.c)

...

\end{document}
于 2010-10-12T14:32:07.210 回答
1

我能想到的唯一合理的方法是创建一个 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/sourcefile.grep

于 2010-10-12T14:33:46.623 回答
1

不久前在 TeX SE 上讨论了这样的事情,一个答案使用了 package catchfilebetweentags。这并不能直接解决您的问题,但也许您可以使用它来提供您想要的片段\lstlistings,也许再次使用临时文件。

于 2010-12-16T00:39:53.363 回答