2

So I know how to create variables and store values from command line.

But normally, I would type my command this way: make run VAR="abc", and VAR will be assigned the new value "abc"

However, if I want to do something like this VAR="abc" make run, how can I change my make file? Right now, if I run this, VAR still has the initial value when it was created in the make file.

This is my make file:

VAR = ""

.PHONY : build run

build : program.c
   gcc -o prog -g program.c

run : build
   ./prog $(VAR)
SusN
  • 31
  • 2

2 Answers2

2

When you write VAR = "", you're overwriting any value VAR might have had (e.g. from the environment, or the command line). You can use a conditional assignment instead, which looks like this:

VAR ?= ""

This sets VAR only if it wasn't set already. It's equivalent to e.g.

ifeq ($(origin VAR), undefined)
  VAR = ""
endif
Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
  • The make manual link discusses `?=` (and gives that equivalent code) in [The Two Flavors of Variables](http://www.gnu.org/software/make/manual/make.html#Flavors). – Etan Reisner Jul 13 '15 at 01:55
  • Also, just for the record `VAR = ""` in make isn't setting `VAR` to an empty string it is setting it to the value `""`. Which is strictly less useful than an empty string to make itself and so really doesn't have any useful purpose and should likely just be dropped entirely. – Etan Reisner Jul 13 '15 at 01:56
0
VAR = ${VAR}

if i remember right