0

I'm trying to build some c programs with gnu make (4.1) through a shell script. I want to use different CFLAGS parameters, which I read from a file. The file contains lines like:

"-O1 -freorder-functions"

I am trying to do something like

while read line
do
    opts="$line"
    make CFLAGS="$opts"
done < $1

but all my attempts end up in the following error:

cc1: error: argument to ‘-O’ should be a non-negative integer, ‘g’, ‘s’ or ‘fast’

So I tried to change the file's contents to only the parameters after -O1 (-freorder-functions), and add the -O1 in the shell script:

opts=$(printf "\"-O%d %s\"", 1, "$line")

(and a lot of other things that seem less sensible) but I still get the same error message.

Hard-coding the parameter to make in the shell script works fine:

make CFLAGS="-O1 -freorder-functions"

Sorry if this is a stupid question, but I can't seem to find any examples of how something like this is done, and I'm new to shell scripting, so I don't really understand how it's treating the variables here. An echo of what I'm attempting to pass to CFLAGS looks okay to me.

mijiturka
  • 434
  • 6
  • 18

1 Answers1

2

With double quotes around the flags in the file and you dutifully quoting your shell variables properly, your make call ends up being

make CFLAGS="\"-O1 -freorder-functions\""

That is to say, with double quotes in the flags. This is passed all the way down to the compiler call, which means that the compiler call is something like

cc "-O1 -freorder-functions" -c foo.c

...which asks the compiler to use optimization level 1 -freorder-functions, and it complains that that is not valid.

To solve this, I would remove the quotes from the file. You could also use opts=$line with $line unquoted, but that is not exactly safe.

Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • Thanks, that gives me an idea of what might be happening. However, in the second case I had removed the quotes from the file, hence the \" in printf. Without them - in something like $(printf "-O%d %s", 1, "$line") - it treats -O as an option to printf. opts=$line unfortunately treats the "-freorder-fucntions" as "-f" and looks for a file called "reorder-functions". – mijiturka Feb 22 '15 at 23:35
  • 1
    Use `$(printf -- "-O%d %s" 1 "$line")`. By convention, option processing ceases after `--`. `printf` from the GNU coreutils follows this convention. – Wintermute Feb 22 '15 at 23:36