tags:

views:

63

answers:

3

Imagine the following folder structure:

  • project
    • src
      • code.c
      • makefile
    • bin

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 better way to do it?

Thanks.

A: 

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.

pajton
A: 

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.

Martinho Fernandes
+4  A: 
Beta
You can also use `../bin/%.o: %.c` as a pattern rule in the Makefile, so you might be able to avoid an explicit `$(MAIN_DIR)` variable.
Dale Hagglund
@Dale Hagglund: I thought of that, but it makes the Makefile less flexible. For instance, you can't move it to a different directory.
Beta
True enough. In larger makefile systems, I usually end up with a `rules.mk` file somewhere at the top of the tree that I include in lower-level makefiles. `rules.mk` would contain a pattern rule like this. The actual makefiles still aren't strictly location-independent, of course, since I have to edit the necessary include paths if I copy them around.
Dale Hagglund
@Dale Hagglund: you can make the lower-level makefiles (somewhat) movable either by using absolute, not relative paths in the include directives, or by using the -I option when you run make, to tell it where to look.
Beta