Multiline bash commands in makefile

2019-01-08 08:57发布

I have a very comfortable way to compile my project via a few lines of bash commands. But now I need to compile it via makefile. Considering, that every command is run in its own shell, my question is what is the best way to run multi-line bash command, depended on each other, in makefile? For example, like this:

for i in `find`
do
    all="$all $i"
done
gcc $all

Also, can someone explain why even single-line command bash -c 'a=3; echo $a > file' works correct in terminal, but create empty file in makefile case?

标签: bash makefile
4条回答
一夜七次
2楼-- · 2019-01-08 09:30

I would use backslash-newline:

foo:
    for i in `find`;     \
    do                   \
        all="$$all $$i"; \
    done;                \
    gcc $$all

UPD.

Or, in case if just want pass the whole list returned by find to gcc:

foo:
    gcc `find`
查看更多
Root(大扎)
3楼-- · 2019-01-08 09:36

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)
查看更多
成全新的幸福
4楼-- · 2019-01-08 09:44

What's wrong with just invoking the commands?

foo:
       echo line1
       echo line2
       ....

And for your second question, you need to escape the $ by using $$ instead, i.e. bash -c '... echo $$a ...'.

EDIT: Your example could be rewritten to a single line script like this:

gcc $(for i in `find`; do echo $i; done)
查看更多
We Are One
5楼-- · 2019-01-08 09:46

As indicated in the question, every sub-command is run in its own shell. This makes writing non-trivial shell scripts a little bit messy -- but it is possible! The solution is to consolidate your script into what make will consider a single sub-command (a single line).

Tips for writing shell scripts within makefiles:

  1. Escape the script's use of $ by replacing with $$
  2. Convert the script to work as a single line by inserting ; between commands
  3. If you want to write the script on multiple lines, escape end-of-line with \
  4. Optionally start with set -e to match make's provision to abort on sub-command failure
  5. This is totally optional, but you could bracket the script with () or {} to emphasize the cohesiveness of a multiple line sequence -- that this is not a typical makefile command sequence

Here's an example inspired by the OP:

mytarget:
    { \
    set -e ;\
    msg="header:" ;\
    for i in $$(seq 1 3) ; do msg="$$msg pre_$${i}_post" ; done ;\
    msg="$$msg :footer" ;\
    echo msg=$$msg ;\
    }
查看更多
登录 后发表回答