Can I compile all .cpp files in src/ to .o#39;s in obj/, then link to binary in ./?(我可以将 src/中的所有 .cpp 文件编译为 obj/中的 .o,然后链接到 ./中的二进制文件吗?)
问题描述
我的项目目录如下:
/project
Makefile
main
/src
main.cpp
foo.cpp
foo.h
bar.cpp
bar.h
/obj
main.o
foo.o
bar.o
我想让我的 makefile 做的是将 /src
文件夹中的所有 .cpp
文件编译成 .o
文件在/obj
文件夹,然后将 /obj
中的所有 .o
文件链接到顶级文件夹 /中的输出二进制文件中项目
.
What I would like my makefile to do would be to compile all .cpp
files in the /src
folder to .o
files in the /obj
folder, then link all the .o
files in /obj
into the output binary in the top-level folder /project
.
我几乎没有使用 Makefile 的经验,也不确定要搜索什么来完成此任务.
I have next to no experience with Makefiles, and am not really sure what to search for to accomplish this.
此外,这是一种好"的方法,还是有更标准的方法来解决我正在尝试做的事情?
Also, is this a "good" way to do this, or is there a more standard approach to what I'm trying to do?
推荐答案
Makefile 部分问题
这很简单,除非你不需要概括尝试类似下面的代码(但用 g++ 附近的制表符替换空格缩进)
This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)
SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...
main.exe: $(OBJ_FILES)
g++ $(LDFLAGS) -o $@ $^
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
<小时>
自动依赖图生成
大多数 make 系统的必须"功能.通过将 -MMD
标志添加到 CXXFLAGS
和 -include $(OBJ_FILES:.o=.d)
到 makefile 正文的末尾:
A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD
flag to CXXFLAGS
and -include $(OBJ_FILES:.o=.d)
to the end of the makefile body:
CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)
正如人们已经提到的,总是有 GNU Make Manual,很有帮助.
And as guys mentioned already, always have GNU Make Manual around, it is very helpful.
这篇关于我可以将 src/中的所有 .cpp 文件编译为 obj/中的 .o,然后链接到 ./中的二进制文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以将 src/中的所有 .cpp 文件编译为 obj/中的 .o,然后链接到 ./中的二进制文件吗?


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01