2

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.

2
  • That's correct: macro expansion happens on export only. Commented Jun 19, 2020 at 20:11
  • Thanks, I was afraid of that. I'll leave the question open for a bit in case someone posts a workaround. Commented Jun 19, 2020 at 20:16

1 Answer 1

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.

2
  • 3
    Alternatively one can use noweb references. Just let one Elisp block -- let's name it blockWithString -- evaluate to the string and refer to that block as noweb function call <<blockWithString()>> in another block. Commented Jun 19, 2020 at 23:51
  • @Tobias Is there any API to get the expanded orgmode macro from elisp? If so, OP's purpose will be achieved. Commented Jul 11 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.