C++ 我可以将 src/ 中的所有 .cpp 文件编译为 obj/ 中的 .o,然后链接到 ./ 中的二进制文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2908057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?
提问by Austin Hyde
My project directory looks like this:
我的项目目录如下所示:
/project
Makefile
main
/src
main.cpp
foo.cpp
foo.h
bar.cpp
bar.h
/obj
main.o
foo.o
bar.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 做的是将.cpp
文件/src
夹中的所有文件编译为文件夹.o
中的/obj
文件,然后将所有.o
文件链接/obj
到顶级文件夹中的输出二进制文件中/project
。
I have next to no experience with Makefiles, and am not really sure what to search for to accomplish this.
我几乎没有使用 Makefile 的经验,并且不确定要搜索什么来完成此任务。
Also, is this a "good" way to do this, or is there a more standard approach to what I'm trying to do?
另外,这是一种“好”的方法,还是有更标准的方法来解决我正在尝试做的事情?
回答by bobah
Makefile part of the question
问题的 Makefile 部分
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++)
这很容易,除非您不需要概括尝试类似下面的代码(但用 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 $@ $<
Automatic dependency graph generation
自动依赖图生成
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:
大多数 make 系统的“必须”功能。通过在makefile 主体的末尾和末尾添加-MMD
标志,可以在单次传递中使用 GCC 作为编译的副作用:CXXFLAGS
-include $(OBJ_FILES:.o=.d)
CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)
And as guys mentioned already, always have GNU Make Manualaround, it is very helpful.
正如人们已经提到的,总是有GNU Make 手册,它非常有帮助。
回答by xesf
Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:
通配符也适用于我,但我想为那些使用目录变量的人提供旁注。始终对文件夹树使用斜杠(而不是反斜杠),否则会失败:
BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib
MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)