Makefile to move .o files to Different Directory

4k Views Asked by At

I have source code in one directory and have a makefile in a different directory. I am able to compile the code using the make system's vpath mechanism. The .o files are being created in the same folder where the makefile is. But I want to move those .o files to a different directory called obj. I tried the following:

vpath %.o obj

However, they are still being created in the same folder as the makefile. Can anyone help me to solve this issue?

Here are some highlighted lines of the makefile:

PATH_TO_OBJ:- ../obj
SRC :- .c files
OBJS :- $(SRC:.c = .o)
.c.o = $(CC) $(CFLAGS) -c 
exe: cc $(LFLAGS) -o $(PATH_TO_OBJ) $(SRC).

After this also, .o file is creating in same folder of Makefile. Not moving to obj

2

There are 2 best solutions below

2
On

-o option defines where to save the output file, produced by a gcc compiler.

gcc main.c -c -o path/to/object/files/main.o
0
On

Make's VPATH is only for finding source files. The placement of object files is up to the thing that is building them. There's a nice description at http://mad-scientist.net/make/vpath.html (I see someone beat me to posting this in a comment).

The *BSD build systems use variants of make that can place object files (and other generated files, including C sources from lex and yacc variants) in /usr/obj automatically. If you have access to that version of make, that will likely be a good way to deal with whatever underlying problem you are trying to solve.