I am building a build system and have .c file which contains version string. const char version[] = "V01.00.00";
I need to get that line by regex into make variable to use for further binary making.
Can you suggest the best way to do that? Would appreciate native make solution.
Asked
Active
Viewed 144 times
0

Karolis Milieška
- 621
- 5
- 15
-
3It might be easier to do it the other way round: Define the version in the Makefile and inject it into the C code (e.g. by defining a macro on the compiler command line via `cc -DVERSION=...`). – melpomene Jun 01 '19 at 20:47
-
See https://stackoverflow.com/questions/6767413/create-a-variable-in-a-makefile-by-reading-contents-of-another-file You could just call some script to do the extraction instead of calling `cat` as in the answer above. This might also help: https://stackoverflow.com/questions/589276/how-can-i-use-bash-syntax-in-makefile-targets or https://stackoverflow.com/questions/49871570/regex-in-makefile – Michi Jun 01 '19 at 22:21
1 Answers
0
It's a bad idea to try to parse .c
files by yourself to extract information from them. Only the C compiler, for example gcc
should be used to parse .c
files. You should not be doing it, leave it to the compiler.
The reason is, that if someone changes the .c
file you extracted information from, your extraction code is likely to break. Basically, your extraction code would have to be compatible with any .c
syntax, which means, you would end up to be a "compiler".
Otherwise, you would have to publish some documentation for other programmers, to tell them to keep the .c
code the way you want it, for your code not to break. So you would end up restricting the C language for them.
If you want to get such information:
- define a function in the
.c
file to return that information - compile that file to a library
- make an executable that links with the library and calls that function
- call that executable from the Makefile

Mark Galeck
- 6,155
- 1
- 28
- 55