0

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.

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

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.

| improve this answer | |
  • 2
    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. – Tobias Jun 19 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.