5

I'm not finding a lot of examples/documentation for the non-REPL world of C/C++ in Emacs org-mode babel. For example, is there a way to break a program up into separate source code blocks, i.e., a block for main, then separate blocks for its func1, func2, ... called by main? Or, is there any way to have just a stand-alone function lonefunc in a block, then call it from another place? I suppose this is all a form of literate programming, but typically you're pulling it all together with tangling. I'd like not to tangle, but have things running in the org-mode session.

147pm
  • 2,907
  • 1
  • 18
  • 39
  • For languages such as C and C++, there is [no direct support](http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-C.html#orgheadline7) of sessions. You'd have to embed in other block types to mimic them as @dfeich has shown in a separate answer below. – Emacs User Feb 10 '17 at 14:35

1 Answers1

3

You can do this by using the noweb reference syntax:

First we define some named code blocks

#+NAME: srcMyfunc
#+BEGIN_SRC C 
  void myfunc() {
    printf("print from function\n");
  }
#+END_SRC  


#+NAME: srcMain
#+BEGIN_SRC C
  int main(int argc,char **argv) {
    printf("Hello World\n");
    myfunc();
    exit(0);
  }
#+END_SRC

Now we define a block which includes the other code blocks by referencing them with the <> syntax (needs the :noweb yes option). We could tangle this block, but we can also execute it directly.

#+BEGIN_SRC C :results output :noweb yes
  #include "stdlib.h"
  #include "stdio.h"

  <<srcMyfunc>>
  <<srcMain>>

  #+END_SRC

#+RESULTS:
: Hello World
: print from function

I prefer to do it in the way that I have one code block for combining all the others, because the <> tend to mess up the language buffer, except when I just want to test an isolated function.

I do not think that this is very useful for bigger programs, but I used it extensively in a parallel programming course to write notes and documentation.

dfeich
  • 1,844
  • 16
  • 16
  • 1
    BTW, I forgot: I keep a number of babel examples for different languages on https://github.com/dfeich/org-babel-examples. – dfeich Jan 11 '17 at 06:43