m4

Conditionally defining macro in m4 within ifdef


This is the first time I'm using m4, and I'm having difficulty in defining a macro conditionally based on whether or not another macro is already defined.

The problem I'm facing is with the following snippet in my test.m4 file:

ifdef(`MANPAGE', define(_NAME, `NAME'), define(_NAME, `Name'))

_NAME

As an analogy in C, what I'm trying to achieve is something like this:

#ifdef MANPAGE
#define _NAME "NAME"
#else
#define _NAME "Name"
#endif

Now, when I run m4 -DMANPAGE test.m4, I get the output Name, whereas I expect the output to be NAME. Whether or not -DMANPAGE is specified, I always get the output Name.

I am uncertain where I'm going wrong, and I was unable to find a solution even after referring to the m4 man pages and other online articles. On StackOverflow, I did refer to the following posts which seemed to have some bearing: Triple conditional check with ifdef in M4 and Escaping Commas in m4 ifdef Statements.

However, I still haven't made any headway. Any pointers would be much appreciated.

Thanks in advance!


Solution

  • Try this:

    ifdef(`MANPAGE', `define(_NAME, `NAME')', `define(_NAME, `Name')')
    

    I believe the parameters get expanded before passing to ifdef