我可以将 src/中的所有 .cpp 文件编译为 obj/中的 .o,然后链接到 ./中的二进制文件吗? [英] Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

查看:18
本文介绍了我可以将 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,然后链接到 ./中的二进制文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆