无法包含用于C编译的文件夹

时间:2019-06-10 06:26:58

标签: c makefile compilation

如果C在外部文件夹中,则所有编译,但是当lib.c在[lib]文件夹中时,它将给出错误:make: *** No rule to make target 'obj/lib.o', needed by 'run'. Stop.

应如何更正makefile以确保编译成功?
修改makefile的正确方法是什么?

树是这样的:

 ├── inc
 │   └── main.h
 ├── lib
 │   └── lib.c
 ├── main.c
 ├── main_functions.sh
 ├── Makefile
 └── test_usages.c

makefile:

# IDIR =../include \
This is a makefile \

IDIR =./inc
CC=gcc

ODIR=obj
# LIB_SRC_DIR =./lib
LDIR =./lib 
CFLAGS=-I $(IDIR) $(LDIR)   ## added $(LDIR)

# header files required
_DEPS = *.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))

_DEP_LIB = *.c                                  ##
DEPS_LIB = $(patsubst %,$(LDIR)/%,$(_DEP_LIB))  ##

_OBJ = lib.o main.o test_usages.o 
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))

 $(ODIR)/%.o: %.c $(DEPS) $(DEPS_LIB)       ## added $(DEPS_LIB)
     $(CC) -c -o $@ $< $(CFLAGS) 

 #%.o: %.c
 #      $(CC) $(CFLAGS) $(INCLUDES) -c $(input) -o $(output)

 # make commands options: make <options>, e.g. make hello_make  
 # executable name
 hello_make: $(OBJ)
     gcc -o $@ $^ $(CFLAGS)

 run: $(OBJ)
     gcc -o $@ $^ $(CFLAGS)
     echo "=========================================================="
     ./run
     echo "=========================================================="

 .PHONY: clean

 clean:
     echo "cleaning ...." $(ODIR)/*.o
     rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~ ./*.exe

预先感谢您的建议。

1 个答案:

答案 0 :(得分:1)

您的Makefile中有一些怪癖,但这是我的工作方式:

  1. 删除LDIR =./lib行中的尾随空白
  2. 在方便的地方插入VPATH=$(LDIR)

现在make -n run显示(但不运行)所有预期的命令行:

gcc -c -o obj/lib.o ./lib/lib.c -I ./inc ./lib
gcc -c -o obj/main.o main.c -I ./inc ./lib
gcc -c -o obj/test_usages.o test_usages.c -I ./inc ./lib
gcc -o run obj/lib.o obj/main.o obj/test_usages.o -I ./inc ./lib
echo "=========================================================="
./run
echo "=========================================================="

顺便说一句,您可以使用以下选项来调试Makefile

make -npr run打印所有变量,规则等,但不打印内置变量。

make -nd run打印所有决定,很多。

相关问题