c++ - 目标文件生成和使用 makefile 进行链接的最佳实践 - C++

标签 c++ makefile

背景

我刚刚开始在 LINUX 上进行 C++ 编程。在我的最后一个问题中,我询问了将 makefile 用于大型应用程序的最佳实践。 “SO”用户建议阅读 Miller 关于递归 makefile 的论文并避免 makefile 递归(我使用的是递归 makefile)。

我跟随 miller 并创建了一个如下所示的 makefile。以下是项目结构

root
...makefile
...main.cpp
...foo
......foo.cpp
......foo.h
......module.mk

我的 makefile 如下所示

#Main makefile which does the build

CFLAGS =
CC = g++
PROG = fooexe

#each module will append the source files to here
SRC :=

#including the description
include foo/module.mk

OBJ := $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC))) main.o

#linking the program
fooexe: $(OBJ)
    $(CC) -o $(PROG) $(OBJ)

%.o:
    $(CC) -c $(SRC)

main.o:
    $(CC) -c main.cpp

depend:
    makedepend -- $(CFLAGS) -- $(SRC)

.PHONY:clean
clean:
    rm -f *.o

这是 foo 目录中的 module.mk

SRC += foo/foo.cpp

当我运行 make -n 时,我得到以下输出。

g++ -c  foo/foo.cpp
g++ -c main.cpp
g++ -o fooexe  foo/foo.o main.o

问题

  • 我应该在哪里创建对象 (.o) 文件?单个目录中的所有目标文件还是它自己的模块目录中的每个目标文件?我的意思是哪个是生成 foo.o 的最佳位置?它是在 foo 目录中还是在根目录中(我的示例在根目录中生成)?
  • 在提供的示例中,g++ -c foo/foo.cpp 命令在根目录中生成 .o 文件。但是当链接 (g++ -o fooexe foo/foo.o main.o) 时,它正在寻找 foo/foo.o。我该如何纠正?

任何帮助都会很棒

最佳答案

  • Where should I create the object(.o) files? All object files in a single directory or each object files in it's own modules directory? I mean which is the best place to generate foo.o? Is it in foo directory or the root (My example generates in the root)?

我发现将目标文件本地化到模块级目录下的单独目录中更容易调查失败的构建。

foo
    |_ build
    |_ src 

根据项目的大小,这些目标文件被分组以形成更高级别的组件等等。所有组件都进入主构建目录,主应用程序可以从该目录运行(具有所有依赖库等)。

  • In the provided example, g++ -c foo/foo.cpp command generates the .o file in the root directory. But when linking(g++ -o fooexe foo/foo.o main.o) it is looking for the foo/foo.o. How can I correct this?

使用:

 g++ -o fooexe  foo.o main.o

关于c++ - 目标文件生成和使用 makefile 进行链接的最佳实践 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/780429/

相关文章:

c++ - vector 保持内存甚至与另一个空 vector 交换

c - 解决 "variable ' xxx 的最佳方法已声明但从未被引用”

c++ - 当我包含 header 时,C++无法编译

c++ - 设置Makefile在另一个目录中构建

makefile - 无法安装最新的 ejabberd 和 Erlang 版本 Ubuntu 14.04 LTS

c++ - 非复制 std::shared_ptr<boost::any>?

c++ - 无法创建动态文件夹名称

C++ 比较迭代器和 int

makefile - 使用-fPIC选项重新编译,但该选项已在makefile中

c++ - 如何 make_shared 计数次,分配不同的区域而不重复循环?