Why do conditionals in autoconf scripts prefix variables with "x"?
Asked Answered
A

2

7

Why do conditional statements in autoconf scripts prefix their variables with "x"? For example, the macro provided by GNU to test for Boost has conditionals such as

if test "x$want_boost" = "xyes"; then

Why is this not defined as:

if test "$want_boost" = "yes"; then
Aught answered 29/6, 2012 at 16:50 Comment(0)
R
10

In some early shells, testing for an empty string variable wasn't as easy as it is now, so the best alternative was to see if "x$variable" was equal to just "x". Also, since that's apparently using test, that's simpler than trying to properly quote/escape sequences like '$x != "y"' without losing sanity and/or portability.

Rumph answered 29/6, 2012 at 16:53 Comment(4)
To clarify: "wasn't as easy as it is now" means that many shells were buggy and would not properly evaluate commands with an empty string like test "" = "foo"Dap
The other reason this is necessary is that if $variable expands to something that begins with a dash, test might interpret that as an option rather than a string to be compared. In modern shells, the equals sign takes precedence, but it was not always so.Brummett
@Brummett your comment should be the answer, please make it one.Appetite
@Appetite Eh, sure, why not.Brummett
B
3

In POSIX-compliant shells,

test "$foo" = "$bar"

does a string comparison no matter what the contents of the variables foo and bar are. But in old, noncompliant shells, if foo contained something that begins with a dash, test would try to interpret that as a unary operator, so it would either throw a syntax error or do the wrong test. Writing x"$foo" = x"$bar" makes that impossible. I also vaguely recall problems if either argument expanded to the empty string, but that might have only been if you left out the double quotes (in which case it would be a problem with a modern shell, too).

This is particularly relevant when writing configure scripts, because, at least in principle, they're supposed to work no matter how old the shell environment is; and if you're writing a new program today, in 2020, the most plausible reason why you'd use C and autoconf is that you need portability to some old systems...

Brummett answered 19/3, 2020 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.