Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in makefiles (How to use arrays)

Tags:

makefile

I have compiler flag in a makefile which looks like:

MYVARIABLE1=HELLO 4.5.6
MYVARIABLE2"="{0x95,0x04,0x05,0x06,' ','A','A'}"
CFLAGS+=-DMYVARIABLE2=${MYVARIABLE2}

which works fine. But if I want to use already known info in VARIABLE1 to create VARIABLE2:

MYVARIABLE1=HELLO 4.5.6
MYVARIABLE2"="{0x95,$(MYVARIABLE1[7]},$(MYVARIABLE1[9]},$(MYVARIABLE1[11]},' ','A','A'}"
CFLAGS+=-DMYVARIABLE2=${MYVARIABLE2}

But when I run my makefile with the second option, It stops compile at the c-file using the CFLAG with the error message:

error: expected expression before ',' token

in the C-code:

 uint8 OTHERVARIABLE[]            =  MYVARIABLE2;

Question: Is the really $(MYVARIABLE1[x ]}the correct way of using parts of a variable defined in the makefile?

like image 253
Sharky Avatar asked Apr 23 '18 14:04

Sharky


People also ask

What does $@ mean in makefiles?

The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.

How do I get environment variables in makefile?

Unfortunately, Makefile doesn't automatically have access to the root . env file, which might look something like this. That said, we can include the appropriate environment file in our Makefile . The environment variables are then accessible using the $(VAR_NAME) syntax.


2 Answers

There is no such thing as an "array" or list variable in make syntax.

There are some GNU make functions which will operate on every word of a string, one at a time, where a word is a space-separated value. This can be thought of as an array, kind of. This is why make has an almost impossible time dealing with paths containing whitespace.

If you're not using GNU make, then none of this will work.

To do what you want you'll have to split the MYVARIABLE1 value into separate words, then you can access individual words using functions. Something like this will work:

MYVARIABLE1 = HELLO 4.5.6
__var1 = $(subst ., ,$(MYVARIABLE1))
MYVARIABLE2 = "{0x95,$(word 2,$(__var1)),$(word 3,$(__var1)),$(word 4,$(__var1)),' ','A','A'}"

The subst function replaces the . with spaces, giving a result of HELLO 4 5 6 so that you can reference the parts of the version individually using the word function.

You can find out more about GNU make functions in the documentation.

like image 157
MadScientist Avatar answered Oct 04 '22 20:10

MadScientist


Is the really $(MYVARIABLE1[x]} the correct way of using parts of a variable defined in the makefile?

It is valid bash syntax, but not valid GNU make syntax.

like image 26
Maxim Egorushkin Avatar answered Oct 04 '22 21:10

Maxim Egorushkin