Tim
Tim

Reputation: 1933

Including another Makefile results in a failed build, why?

Problem

Including an external Makefile makes my previously stable build fail with the following error :

make: *** No rule to make target 'build/main.o', needed by 'all'. Stop.

Context

The context is that I currently manage the build of each of my projects with one Makefile per project. Since the projects Makefiles have a lot of redundancy, I want to put the common things in an external Makefile that will be included in each project's Makefile.

Minimal example to reproduce the issue

In this simple and minimalist example I try to build srcs/main.c into build/main.o and I also try to display what is inside the variable FOO which in is tools.mk :

Folder structure :

|   Makefile
|
+---build
|       (main.o)
+---mkf
|       tools.mk
|
\---srcs
        main.c

Content of Makefile :

include ./mkf/tools.mk

mkfile_path :=$(realpath $(lastword $(MAKEFILE_LIST)))
current_dir :=$(dir $(mkfile_path))

VPATH = $(current_dir)/srcs
./build/%.o: %.c
    @echo $< $@
    gcc $< -o $@

all: ./build/main.o test
    @echo Done ! 

test:
    @echo Testing include : $(FOO)  

.PHONY: all test

Content of tools.mk :

FOO = 42

Content of main.c (basic hello world) :

# include <stdio.h>
# include <stdlib.h>

int main(void)
{   
    printf("Hello, world!");
    return EXIT_SUCCESS;
} /*main*/

Now basically my problem is that if I place myself in the root folder and type make all, the build will fail with the error mentioned above. However if I comment the line include ./mkf/tools.mk the build succeeds. Thus I guess it fails because of the include line, but I cannot figure out why.

Can someone enlighten me on this ?

The build is performed with GNU Make 4.2 on Windows 7 64-bits.

Upvotes: 0

Views: 364

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

In

mkfile_path :=$(realpath $(lastword $(MAKEFILE_LIST)))

That yields the path of the last included makefile, which is ./mkf/tools.mk. See Other Special Variables for details.

A fix:

mkfile_path :=$(realpath $(lastword $(MAKEFILE_LIST)))
current_dir :=$(dir $(mkfile_path))
include ./mkf/tools.mk

Upvotes: 1

Related Questions