nunos
nunos

Reputation: 21389

Makefile - How to save the .o one directory up?

Imagine the following folder structure:

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.

Upvotes: 4

Views: 4600

Answers (4)

ladislas
ladislas

Reputation: 3070

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

Upvotes: 3

Beta
Beta

Reputation: 99094

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)...
    

Upvotes: 6

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234434

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.

Upvotes: 0

pajton
pajton

Reputation: 16226

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.

Upvotes: 0

Related Questions