When I compile my C files and output the resulting object files into their own directory, I need to make sure this directory exists.
I have seen two approaches for this:
- Always create the directory of the current target:
<code>obj/%.o: src/%.c@mkdir -p $(@D)$(CC) ...</code><code>obj/%.o: src/%.c @mkdir -p $(@D) $(CC) ... </code>
obj/%.o: src/%.c @mkdir -p $(@D) $(CC) ...
- Add the
obj/
directory as a prerequisite<code>obj/%.o: src/%.c | obj/$(CC) ...obj/:mkdir -p $@</code><code>obj/%.o: src/%.c | obj/ $(CC) ... obj/: mkdir -p $@ </code>obj/%.o: src/%.c | obj/ $(CC) ... obj/: mkdir -p $@
From 1.
I like that it uses $(@D)
to avoid repetition and to make it more robust, from 2.
I like that mkdir
is called only once and I feel like it makes more sense conceptually.
When I try to combine both like this
obj/%.o: src/%.c | $(@D)
$(CC) ...
obj/:
mkdir -p $@
then the compiler will complain that the obj/
directory does not exist.
Daniel Engel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.