8

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?

Sharky
  • 323
  • 1
  • 3
  • 11

2 Answers2

9

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.

MadScientist
  • 92,819
  • 9
  • 109
  • 136
  • Thank you for this information! I had a little bit of trouble what to search for in the GNU make documentation since array was totally wrong as a search string ;). With this approach, it works. – Sharky Apr 24 '18 at 05:49
1

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271