Search code examples
cmakefile

Makefile - place .o files into a subfolder


I have a simple makefile:

run: myprogram
    ./myprog.out

myprogram: main.o otherfile.o
        gcc -o myprog.out main.o otherfile.o
    
%.o : %.c
    gcc -c $<

right now this puts all the .o files next to my c and h files which is annoying. I want to have a subfolder called "myObj" for example where all the .o files get dumped into, but still want it to build myprog into the root folder. Online examples for this problem are all overly complex and i'm not sure what exact lines in them are essential for me to achieve this, but they seem to all have the basic $(OBJDIR)/%.o : %.c in common. So i try:

OBJDIR=myObj

run: myprogram
    ./myprog.out

myprogram: main.o otherfile.o
        gcc -o myprog.out main.o otherfile.o
    
$(OBJDIR)/%.o : %.c
    gcc -c $<

however this does exactly the same thing and dumps all the .o files in the root folder. How, can i get them to go in the subfolder?


Solution

  • As mentioned in comments, you need to specify that the .o files are in the subdirectory in your rule that links the binary, and also your rule to compile the .c files needs to specify the output file (in the subdirectory).

    You also have some other weird things. run depends on a file called myprogram which will never exist, and runs a command called myprogram.out.

    Likewise, you have a rule that claims to build a file called myprogram, but actually builds a file called myprogram.out.

    These will probably result in your code being recompiled (or relinked) needlessly. Each rule should build the file it claims to build. So you probably want something like this:

    OBJDIR = myObj
    
    run:    myprogram
            ./myprogram
    
    myprogram: $(OBJDIR)/main.o $(OBJDIR)/otherfile.o
        gcc -o $@ $^
    
    $(OBJDIR)/%.o : %.c | $(OBJDIR)
        gcc -c $^ -o $@
    
    $(OBJDIR):
        mkdir $@