Search code examples
cemacsorg-modeorg-babel

Run a C's completed program from org babel


I tried to run a sample from C Primer Plus:

Listing 2.1 The first.c Program
#+BEGIN_SRC C :results output
#include <stdio.h>
int main(void)                /* a simple program             */
{
    int num;                  /* define a variable called num */
    num = 1;                  /* assign a value to num        */

    printf("I am a simple "); /* use the printf() function    */
    printf("computer.n");
    printf("My favorite number is %d because it is first.n",num);

    return 0;
}
#+END_SRC

It report mysterious errors as:

/tmp/babel-xEtnj6/C-src-mefAEj.c:9:15: error: stray ‘\302’ in program
    9 | int main(void)                /* a simple program             */
      |               ^
/tmp/babel-xEtnj6/C-src-mefAEj.c:9:16: error: stray ‘\240’ in program
    9 | int main(void)                /* a simple program             */
      |                ^
/tmp/babel-xEtnj6/C-src-mefAEj.c:9:17: error: stray ‘\302’ in program
    9 | int main(void)                /* a simple program             */

If main() was removed, it works:

#+BEGIN_SRC C
printf("Literature Programming");
#+END_SRC

#+RESULTS:
: Literature Programming

Unfortunately, most C code is encapsulated in 'main`.

How could I get the first example working?


Solution

  • You can try by adding :main no to your code block

    #+BEGIN_SRC C :results output :main no
    #include <stdio.h>
    
    int main(void)                /* a simple program             */
    {
        int num;                  /* define a variable called num */
        num = 1;                  /* assign a value to num        */
    
        printf("I am a simple "); /* use the printf() function    */
        printf("computer.n");
        printf("My favorite number is %d because it is first.n",num);
    
        return 0;
    }
    #+END_SRC
    

    Also note that there are other useful modifiers like :flags, :lib, :cmdline... See Header Arguments for C, C++, D Source Code Blocks for further details.