Q:

How to set the value of a macro using environment variable or command line in verilog?

I want to define a macro during runtime in Verilog using environment variable.
For example, I want to print some text to a file only when the DEBUG macro is defined as 1.
`define DEBUG 0
...
if(DEBUG) $fwrite(file,"Debug message");

How can I override the definition of DEBUG to 1 when running the simulation from command line or using environment variable?
Alternatively, I could keep the macro undefined and use ifdef
`ifdef(DEBUG) $fwrite(file,"Debug message");

In this case I would have to define the macro DEBUG when running the simulation. Is this possible?
I am using Modelsim. Thanks.

EDIT: The accepted answer is sufficient. But I will add this information too for anyone who stumbles upon here.
The value of a parameter can be set/overriden by using -g<parameter> or -G<parameter> argument to vsim. -g sets the parameter value only if it hasn't been set already and -G set the value even if it's defined. I found this convenient when I control simulation length using parameter. Recompilation isn't necessary.
vsim -c work.top -gSIM_END_TIME // Sets value in all scope
vsim -c work.top -g/top/dut/SIM_END_TIME // Sets value only in the defined scope

A:

You can override a macro definition with the vlog command line option +define+<macro_name>[=<macro_text>]
The better option is to leave the macro undefined and use the  `ifdef statement to test if you have defined it on the command line.
Note that using a macro requires you to recompile your source code every time you want to change the macro value. Verilog provides $test$plusargs and $value$plusargs to test command line options at runtime so you do not need to recompile.

