Can makefiles be assigned values ​​read from source files?

Suppose there is a C program that stores its version globally char*in main.c. Can buildsystem (gnu make) somehow retrieve the value of this variable during build so that the embedded executable can have the exact version name as it appears in the program?

What I would like to achieve is that, given the source:

char g_version[] = "Superprogram 1.32 build 1142";

the built system will create an executable file with the name Superprogram 1.32 build 1142.exe

+5
source share
4 answers

:

char g_version[] = VERSION;

make -D

gcc hack.c -DVERSION=\"Superprogram\ 1.99\"

, , sed/grep/awk .., .

+5

unix (grep, sed, awk, perl, tail,...) Makefile, .

+1

#define (, arv library).

, :

// myversion.h
#define  __MY_MAJOR__ 1
#define  __MY_MINOR__ 8

Makefile:

# Makefile
source_file := myversion.h
MAJOR_Identifier := __MY_MAJOR__
MINOR_Identifier := __MY_MINOR__

MAJOR := `cat $(source_file) | tr -s ' ' | grep "\#define $(MAJOR_Identifier)" | cut -d" " -f 3`
MINOR := `cat $(source_file) | tr -s ' ' | grep '\#define $(MINOR_Identifier)' | cut -d" " -f 3`

all:
  @echo "From the Makefile we extract: MAJOR=$(MAJOR) MINOR=$(MINOR)"

Here I used several tools to make it more reliable:

  • tr -s ' ': remove excess space between elements,
  • grep: select a unique line that matches our goal,
  • cut -d" " -f 3: extract the third element of the selected row, which is the target value!

Note that define values ​​can be anything (not just numeric).

Beware of using :=(not =): fooobar.com/questions/102554 / ...

0
source

All Articles