Alf
Alf

Reputation: 1989

How to set in a Makefile the folder in which files are created?

I have my project organized such that all code-files are found in a subdirectory code/. I have two Makefiles, one in the main directory and one in the code/ subdirectory.

The Makefile in the main directory contains (props to that post):

# .PHONY rule means that project_code is not a file that needs to be built
.PHONY: project_code

project_code:
    $(MAKE) -C $(CODE_DIR)

clean:
    $(MAKE) -C $(CODE_DIR) clean

all: exe

The Makefile in the code/ subdirectory contains something like:

exe: $(OBJECTS)
    $(CC) $(CFLAGS) -o $@ $^ -fopenmp -lpng

%.o: %.c
    $(CC) $(CFLAGS) -c $< 

When I am now running make from the main directory, the exe file is created in the code/ subdirectory, but I would like to have it in the main directory. My question: How can I achieve this?

Upvotes: 1

Views: 565

Answers (1)

Peter K.
Peter K.

Reputation: 134

Please reffer this example:

#Name of outpu binary (exe) file;
PROGRAM_NAME := prog

# project dirs
export SRC_DIRS     := ./src1 ./src2
export INCLUDE_DIRS := ./include

#list of source files (with whitespace between them)
SRC_FILES := $(foreach dirname, $(SRC_DIRS), $(wildcard $(dirname)/*.c))

#Object files
OBJ_FILES := $(foreach filename, $(SRC_FILES), $(filename:.c=.o))

# Include flags
LOCAL_INCLUDES=$(foreach dirs, $(INCLUDE_DIRS), -I$(dirs))


# list of lib-flags for compiler. For example for math.h use    -lm
#LIB_FLAGS=-lm
CC=gcc
CFLAGS=-Wall $(LIB_FLAGS) $(LOCAL_INCLUDES)

#build executable file
$(PROGRAM_NAME): $(OBJ_FILES)
        @echo "Build executable"
        @$(CC) $(CFLAGS) -o $@ $^

# compile all object file
%.o: %.c
        @echo "Compile $(notdir $<)"
        @$(CC) -c $(CFLAGS) $< -o $@

#clean all
clean:
        @rm -f $(OBJ_FILES) $(PROGRAM_NAME)

It has only 1 Makefile. It takes sources from listed directories, create objects in same directories and then link to binary in current (top) dir

Upvotes: 1

Related Questions