首页 > 解决方案 > put OBJ files in subdirectory in MAKEFILE

问题描述

my basic Makefile create the .o without the need of writing a line with gcc :

NAME = libtest.h
CC = gcc
CFLAGS = -I. -c
SRCS = example01.c \
       example02.c
OBJ = $(SRCS:.c=.o)

all: $(NAME)
$(NAME): $(OBJ)
       ar -rc $@ $<

I suppose that the rule $(SRCS:.c=.o) is making an equivalent as running $(CC) $(CFLAGS) -o $@ $< because i didn't need to call for the compiler explicitly ?

But then when I try to do the same with the add of a subdirectory in wich goes the OBJ files it doesn't work :

NAME = libtest.h
CC = gcc
CFLAGS = -I. -c
SRCS = example01.c \
       example02.c
ODIR = ./builds
OBJ = $(addprefix $(ODIR)/, $(SRCS:.c=.o))

all: $(NAME)
$(NAME): $(OBJ)
       ar -rc $@ $<

The subdirectory already exist in this example of course. The error output is : No rule to make target 'builds/example01.o', needed by 'libtest.a' I saw solutions that both explicitly call the compiler and have the rule $(SRCS:.c=.o) but i feel like it calls for the compiler two times with no need then ?

标签: makefilegnu-make

解决方案


这个:

我想规则 $(SRCS:.c=.o) 相当于运行 $(CC) $(CFLAGS) -o $@ $<

不太对。如果您不定义自己的规则,Make 有一套内置的模式规则可以应用。其中之一告诉它如何foo.o从文件构建foo.c文件。

但是 make 没有内置规则告诉它如何./builds/foo.o从文件构建foo.c文件,因此您必须自己提供:

$(ODIR)/%.o : %.c
         $(COMPILE.c) -o $@ $<

(这使用了一个内置变量COMPILE.c,这是内置规则使用的;当然你可以定义你自己的)。


推荐阅读