Export C # defines as shell variables

In my project, several paths to various directories, files and other components of the system are stored as #define in filenames.h , a file that contains everything you need. It works well for all binaries generated by compilation, but the project also includes several shell scripts that use the same paths. Currently, this means that as the path changes, all I have to do is edit filenames.h and recompile to get a set of executables to understand the new path, but I need to manually edit each shell script.

So, the question is how to make #defines in shell variables, for example, generate several filenames.sh scripts that will be called from other scripts to initialize them. For example:

 #define TMP_PATH "/ait/tmp/" #define SYNCTMZFILE TMP_PATH "sync_tmz" 

will create

 TMP_PATH="/ait/tmp/" SYNCTMZFILE="/ait/tmp/sync_tmz" 

Of course, you could write a C program that created it (even prints it to stdout and then runs it in the opposite direction in the shell), but I would prefer a simpler, more reliable method, say, they write half-shell halfway, like , for example, through cpp , will create the correct output or something like that.

+4
source share
3 answers

Put this in your Makefile:

 filenames.sh: filenames.h awk '/^#define/{print;printf "_%s=%s\n",$2,$2}' $< \ | cpp -P \ | sed 's/^_//;s/" "//;' > $@ 
+1
source

The converse - saving the host as a shell script and creating a header from this - would be easier. If your title is very stylized, you can write a shell script (or use awk / sed / perl / ...) to parse it and generate a shell fragment.

+1
source

If you create your program using make , and shell scripts are executed by make as part of the build process, you can rotate it:

  • One-page variables in the Makefile .
  • Export them to your shell scripting environment.
  • Pass them to the C compiler as command line parameters. (It is assumed that your compiler supports the -D option or something similar.)

Example (untested):

 export TMP_PATH := /ait/tmp/ export SYNCTMZFILE := $(TMP_PATH)sync_tmz CFLAGS += -DTMP_PATH="$(TMP_PATH)" -DSYNCTMZFILE="$(SYNCTMZFILE)" 

If you do not use make , the -D option can still be useful to you: you can use only one source of variables in the shell of the script, and not in the header file.

0
source

Source: https://habr.com/ru/post/1301098/


All Articles