Search code examples
m4

How can you do an ifdef guard for m4 macro file includes?


For C header files, you can prevent multiple inclusion of a header file like:

#ifndef MY_FOO_H
#define MY_FOO_H

[...]

#endif

How can I do the same thing in m4 such that multiple include() macro calls to the same file will only cause the contents to be included once?

Specifically, I want to do an ifdef guard that involves using macro changequote ( I'll not clutter my code with dnl's):

Originally, when I do the following, multiple inclusions still corrupts the quotes:

changequote_file.m4:

ifdef(my_foo_m4,,define(my_foo_m4,1)
changequote([,])
)

changequote_invocation.m4:

include(changequote_file.m4)
After first include invocation:
[I should not have brackets around me]
`I should have normal m4 quotes around me'
include(changequote_file.m4)
After second include invocation:
[I should not have brackets around me]
`I should have normal m4 quotes around me'

Invoked with m4 changequote_invocation.m4 yields:

After first include invocation:
I should not have brackets around me
`I should have normal m4 quotes around me'


After second include invocation:
[I should not have brackets around me]
`I should have normal m4 quotes around me'

Solution

  • The most straightforward way is an almost-literal translation of the cpp version:

    ifdef(`my_foo_m4',,`define(`my_foo_m4',1)dnl
    (rest of file here)
    ')dnl
    

    So if my_foo_m4 is defined, the file expands to nothing, otherwise its contents are evaluated.