I used this article http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/ to create my makefile (shown below), but sometimes when I run make, some of my object files are created in the home directory (~/). There is something wrong with my Makefile? This method can be used also with g++, or changes must be made?
# Based on http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/
# Git version: https://stackoverflow.com/questions/1704907/how-can-i-get-my-c-code-to-automatically-print-out-its-git-version-hash
# ----------------------------------------
# Project definitions
# ----------------------------------------
# Name of the project
EXEC = foo
# Folders
ODIR = .obj
DDIR = .deps
SDIR = src
# .c files
SRC = $(wildcard $(SDIR)/*.c)
# .h files
INC = $(wildcard $(SDIR)/*.h)
# .d files
DEPS = $(subst .c,.d,$(subst $(SDIR),$(DDIR),$(SRC)))
# Object files
OBJ = $(subst .c,.o,$(subst $(SDIR),$(ODIR),$(SRC)))
# ----------------------------------------
# Compiler and linker definitions
# ----------------------------------------
# Compiler and linker
CC = gcc
CPP = g++
# GIT version
GIT_VERSION := "$(shell git describe --abbrev=4 --dirty --always --tags)"
# Flags for compiler
CFLAGS = -g -W -Wall -Wextra -pedantic -std=c99 -DVERSION=\"$(GIT_VERSION)\"
CPPFLAGS = -g -W -Wall -Wextra -pedantic -std=c99 -DVERSION=\"$(GIT_VERSION)\"
DEPFLAGS = -MT $@ -MMD -MP -MF $(DDIR)/$*.Td
COMPILE.c = $(CC) $(DEPFLAGS) $(CFLAGS)
COMPILE.cpp = $(CPP) $(DEPFLAGS) $(CPPFLAGS)
POSTCOMPILE = mv -f $(DDIR)/$*.Td $(DDIR)/$*.d && touch $@
# ----------------------------------------
# Fomating macros
# ----------------------------------------
BOLD = \033[1m
NORMAL = \033[0m
RED = \033[0;31m
GREEN = \033[0;32m
# ----------------------------------------
# Compilation and linking rules
# ----------------------------------------
all: $(EXEC)
$(EXEC): $(OBJ)
@ echo "${GREEN}Building binary: ${BOLD}$@${GREEN} using dependencies: ${BOLD}$^${NORMAL}"
$(COMPILE.c) $(filter %.c %.s %.o,$^) -o $@
touch $@
$(ODIR)/%.o : $(SDIR)/%.c
$(ODIR)/%.o : $(SDIR)/%.c $(DDIR)/%.d | $(DDIR) $(ODIR)
@ echo "${GREEN}Building target: ${BOLD}$@${GREEN}, using dependencies: ${BOLD}$^${NORMAL}"
$(COMPILE.c) -c $(filter %.c %.s %.o,$^) -o $@
$(POSTCOMPILE)
$(DDIR)/%.d: ;
.PRECIOUS: $(DDIR)/%.d
-include $(DEPS)
# ----------------------------------------
# Script rules
# ----------------------------------------
$(DDIR):
mkdir -p $@
$(ODIR):
mkdir -p $@
clean:
rm -fr $(ODIR)/ $(DDIR)/ $(EXEC) *~ env.mk
remade: clean all
.PHONY: all clean remade
# ----------------------------------------