【问题标题】:Save object files in same makefile directory using depend使用depend将目标文件保存在同一makefile目录中
【发布时间】:2017-01-04 02:55:54
【问题描述】:

我有这个makefile

appname := fun

srcfiles := $(shell find .. -name "*.cpp")
headerfiles := $(shell find .. -name "*.hpp")
objects  := $(patsubst %.cpp, %.o, $(srcfiles))


all: $(srcfiles) $(appname)

$(appname): $(objects)
    $(CXX) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles) $(headerfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(appname) $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

makefile 的父目录包含所有代码(.hpp.cpp 文件)。不幸的是,.o 文件保存在源代码中,而我希望它们保存在可执行文件的同一目录中(和makefile)。这与 Eclipse CDT 中的 Default 相同。

如何修改makefile 才能做到这一点?

PS:我发现了类似的问题,比如this 之一,但没有一个使用depend 来定义$(objects) 任务(它们都是`%.o% 形式)。

【问题讨论】:

    标签: c++ c makefile


    【解决方案1】:

    当您设置objects 变量时,您只需获取.cpp 文件的完整路径名并将后缀替换为.o。所以如果你有一个像my/sub/dir/foo.cpp 这样的文件,那么objects 将包含路径my/sub/dir/foo.o。因此,当然,当您编写规则$(appname): $(objects) 时,make 将尝试构建文件my/sub/dir/foo.o。如果你希望它只构建foo.o,那么你也必须去掉路径,而不仅仅是替换后缀:

    objects := $(patsubst %.cpp,%.o,$(notdir $(srcfiles)))
    

    现在,当然,make 会说它不知道如何构建 foo.o,因为默认规则只知道如何从 .cpp 构建 .o,而不是从隐藏的 .cpp 文件中构建在my/sub/dir

    要使这项工作最简单的解决方案是use VPATH,您可以从您从srcfiles 获得的目录列表中构造VPATH 的值,如下所示:

    VPATH := $(sort $(dir $(srcfiles)))
    

    您也可以考虑使用更好的依赖生成解决方案,例如the one described here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2016-03-04
      • 1970-01-01
      • 2012-05-29
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多