I'm trying to write a bash script that will take in an optional argument, and based on the value of that argument, compile code using that argument as a preprocessor directive. This is my file so far:

#!/bin/bash

OPTIMIZE="$1"

if[ $OPTIMIZE = "OPTIMIZE" ] then
    echo "Compiling optimized algorithm..."
    gcc -c -std=c99 -O2 code.c -D $OPTIMIZE
else
    echo "Compiling naive algorithm..."
    gcc -c -std=c99 -O2 code.c 
fi

However, it doesn't seem to like the "-D" option, complaining that there is a macro name missing after -D. I was under the impression -D defines a new macro (as 1) with name of whatever is specified. I wanted "OPTIMIZE" to be the name of that macro. Any hints?

有帮助吗?

解决方案

The -D should be glued to the name (ie -DFOO not -D FOO)

     gcc -c -std=c99 -Wall "-D$OPTIMIZE" -O2 code.c

and you forgot to pass -Wall to gcc. It is almost always useful.

BTW, you might consider (even for a single file) using make with two phony targets: the default one (e.g. plain), and an optimized one.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top