gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:28:19 24 4
gpt4 key购买 nike

背景

我刚刚开始在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com