Question

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'
Was it helpful?

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.

OTHER TIPS

I think there are in fact 2 question in yours : - How to do it - why it doesn't work in my case.

The way to do it is almost as you've done, but you need to quote everything

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

The problem is the second time you include the file, the quote have been changed, so you should in theory include the following file (you've change the quote to [,] so all the files you include from now should use [,] shouldn't they ?):

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

but you include the same file with the original quote therefore Youw ifdef is on the symbol `my_foo_m4' (which is probably invalid) not my_foo_m4 and the else bit

define(`my_foo_m4',1)
  changequote([,])

is not quoted (not between []) and so evaluated whatever the result of the test is, meaning it call changequote with , , ie it calls

changequote(,)

Which disable the quote.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top