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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:27:28  来源:igfitidea点击:

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

c++build-processmakefile

提问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 .cppfiles in the /srcfolder to .ofiles in the /objfolder, then link all the .ofiles in /objinto 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 -MMDflag to CXXFLAGSand -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)