Makefile - How to save the .o one directory up?
Imagine the following folder structure:
- project
- src
- code.c
- makefile
- bin
- src
How can I compile code.c to code.o and directly put it inside bin? I know I could compile it to code.o under src and the do "mv code.o ../bin" but that would yield an error if there were compile errors, right? Even if it works that way, is there a be开发者_Go百科tter way to do it?
Thanks.
The process should or should not "yield an error" depending on what you mean. If there are compiler errors, you'll know it.
That said, there are several ways to do it with make. The best in this case are probably:
- You could put the Makefile in bin. Make is good at using files there to make files here, but not the other way around.
- You could specify the target path in the makefile target:
$(MAIN_DIR)/bin/%.o: %.c $(COMPILE)...
A little late, but if it can be helpful. This is how I get the up one level directory path from where the makefile is.
$(subst $(notdir $(CURDIR)),,$(CURDIR))
if your project looks like that:
~/myProject/
src/
Makefile
#all the .c and .cpp
bin/
#where you want to put the binaries.
$(CURDIR) will output ~/myProject/src
$(subst $(notdir $(CURDIR)),,$(CURDIR)) will output ~/myProject
You could try moving, but only when the compilation was successful using &&
:
code.o: code.c code.h
g++ -c code.c && mv code.o ../
mv code.o ../
will only be executed if g++
returned 0, which is when the compilation was successful. This may not be suitable solution for you if you have very complicated makefile
, but I thought I'd share what I know.
You can still use the move approach and survive compiler errors:
cc -c code.c && mv code.o ../bin
This won't run the "mv" part if the "cc" part fails.
精彩评论