Ian Taylor Ian Taylor - 1 year ago 97
Bash Question

Using the -D name compilation option from a shell script

I'm attempting to write a shell script that will run several tests of my C++ program, redefining a macro each time it runs. I'm trying to use the -D name preprocessor option (see https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html), but I'm consistently getting the warning that the macro is being redefined, and then the program executes without redefining it.

My script is as follows:


#NUMS is number of subdivisions:
for subdiv in 10 100 500 1000
echo NUMS = $subdiv
g++ -D NUMS=$subdiv project01.cpp -o project01 -lm -fopenmp
./project01 >> bezier_results.txt

In my C++ file, project01.cpp, I state:

#define NUMS 1

I've tried leaving out the '1', but that produces errors as well. It's clear that the script isn't actually redefining the macro. Any thoughts? Thanks!

Tim Tim
Answer Source

By defining the macro on the command-line with -DNUMS=100 you've provided a default value.

You're code is then overriding that default value when you do:

#define NUMS 1

The compiler warning is telling you exactly what has happened. Instead consider coding something like this:

#if !defined NUMS
#define NUMS 1

Now the compiler will only redefine NUMS as 1 when it hasn't already been defined (i.e. elsewhere in your source, or in this case the command-line.)