1

Is it possible to use an org-mode #+MACRO: in an org-babel block?

I'm getting this in the #+RESULTS: block when I evaluate the src block with C-c C-c:

    #+MACRO: COMPILE_FLAGS -std=c99 -Wall -Werror -pedantic
    #+begin_src shell
    echo $"{{{COMPILE_FLAGS}}}"
    #+end_src
    
    #+RESULTS:
    : {{{COMPILE_FLAGS}}}

But I expected this:

#+MACRO: COMPILE_FLAGS -std=c99 -Wall -Werror -pedantic
#+begin_src shell
echo $"{{{COMPILE_FLAGS}}}"
#+end_src

#+RESULTS:
: -std=c99 -Wall -Werror -pedantic

The org-mode documentation does not hint that source blocks are treated differently, so am I doing this wrong, or should I use a different approach?

EDIT - I just realized that macro expansion is listed under "exporting" so maybe that's my problem... I am evaluating a code block, not "exporting" a document. But I'd still like a solution to replacing the macros when evaluating a code block.

Alex Shroyer
  • 627
  • 4
  • 12

1 Answers1

2

You can define header vars in various ways, e.g. globally:

#+PROPERTY: header-args :var COMPILE_FLAGS="-std=c99 -Wall -Werror -pedantic"

#+begin_src shell
echo "${COMPILE_FLAGS}"
#+end_src

or in a property drawer in a specific section:

* foo
:PROPERTIES:
:header-args: :var COMPILE_FLAGS="-std=c99 -Wall -Werror -pedantic"
:END:

#+begin_src shell
  echo "${COMPILE_FLAGS}"
#+end_src

or in the source block itself:

* foo
#+begin_src shell :var COMPILE_FLAGS="-std=c99 -Wall -Werror -pedantic"
  echo "${COMPILE_FLAGS}"
#+end_src

You can also specify a language for a header-arg, so that it will only be applied to code blocks of the specified language:

#+PROPERTY: header-args:shell :var COMPILE_FLAGS="-std=c99 -Wall -Werror -pedantic"

And then there are various rules for what supersedes what - see Using Header Arguments for details.

You cannot do it with MACRO, because, as you surmised, macros are only expanded during export.

NickD
  • 27,023
  • 3
  • 23
  • 42
  • 2
    Alternatively one can use [noweb references](https://orgmode.org/manual/Noweb-Reference-Syntax.html). Just let one Elisp block -- let's name it `blockWithString` -- evaluate to the string and refer to that block as noweb function call `<>` in another block. – Tobias Jun 19 '20 at 23:51