m4: Define

1 
1 5.1 Defining a macro
1 ====================
1 
1 The normal way to define or redefine macros is to use the builtin
1 'define':
1 
1  -- Builtin: define (NAME, [EXPANSION])
1      Defines NAME to expand to EXPANSION.  If EXPANSION is not given, it
1      is taken to be empty.
1 
1      The expansion of 'define' is void.  The macro 'define' is
1      recognized only with parameters.
1 
1    The following example defines the macro FOO to expand to the text
1 'Hello World.'.
1 
1      define(`foo', `Hello world.')
1      =>
1      foo
1      =>Hello world.
1 
1    The empty line in the output is there because the newline is not a
1 part of the macro definition, and it is consequently copied to the
1 output.  This can be avoided by use of the macro 'dnl'.  ⇒Dnl,
1 for details.
1 
1    The first argument to 'define' should be quoted; otherwise, if the
1 macro is already defined, you will be defining a different macro.  This
1 example shows the problems with underquoting, since we did not want to
1 redefine 'one':
1 
1      define(foo, one)
1      =>
1      define(foo, two)
1      =>
1      one
1      =>two
1 
1    GNU 'm4' normally replaces only the _topmost_ definition of a macro
1 if it has several definitions from 'pushdef' (⇒Pushdef).  Some
1 other implementations of 'm4' replace all definitions of a macro with
1 'define'.  ⇒Incompatibilities, for more details.
1 
1    As a GNU extension, the first argument to 'define' does not have to
1 be a simple word.  It can be any text string, even the empty string.  A
1 macro with a non-standard name cannot be invoked in the normal way, as
1 the name is not recognized.  It can only be referenced by the builtins
1 'indir' (⇒Indir) and 'defn' (⇒Defn).
1 
1    Arrays and associative arrays can be simulated by using non-standard
1 macro names.
1 
1  -- Composite: array (INDEX)
1  -- Composite: array_set (INDEX, [VALUE])
1      Provide access to entries within an array.  'array' reads the entry
1      at location INDEX, and 'array_set' assigns VALUE to location INDEX.
1 
1      define(`array', `defn(format(``array[%d]'', `$1'))')
1      =>
1      define(`array_set', `define(format(``array[%d]'', `$1'), `$2')')
1      =>
1      array_set(`4', `array element no. 4')
1      =>
1      array_set(`17', `array element no. 17')
1      =>
1      array(`4')
1      =>array element no. 4
1      array(eval(`10 + 7'))
1      =>array element no. 17
1 
1    Change the '%d' to '%s' and it is an associative array.
1