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

查看:232
本文介绍了我可以编译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 do将把 / src 文件夹中的所有 .cpp 文件编译为 .o 文件夹中的 / code>文件,然后链接<$ c中的所有 .o 文件$ c> / obj 添加到顶层文件夹 / project 中的输出二进制文件中。

我没有Makefiles的经验,也不知道要搜索什么来完成这个。



此外,这是一个好的方式

解决方案

Makefile的一部分问题



这很容易,除非你不需要泛化
尝试类似下面的代码在g ++附近的标签)

  CPP_FILES:= $(wildcard src / *。cpp)
OBJ_FILES:= $(addprefix obj /,$(notdir $(CPP_FILES:.cpp = .o)))
LD_FLAGS:= ...
CC_FLAGS:= ...
b $ b main.exe:$(OBJ_FILES)
g ++ $(LD_FLAGS)-o $ @ $ ^

obj /%。o:src /%。cpp
g ++ $(CC_FLAGS)-c -o $ @ $<






自动生成依赖图



大多数制造系统的必须功能。通过将 -MMD 标志添加到 CC_FLAGS ,可以通过单次传递作为编译的副作用完成GCC。和 -include $(OBJFILES:.o = .d)到makefile正文的结尾:

  CC_FLAGS + = -MMD 
-include $(OBJFILES:.o = .d)

和刚才提到的人一样,总是有 GNU Make Manual ,非常有帮助。


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.

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 part of the question

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++)

CPP_FILES := $(wildcard src/*.cpp)
OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.o)))
LD_FLAGS := ...
CC_FLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LD_FLAGS) -o $@ $^

obj/%.o: src/%.cpp
   g++ $(CC_FLAGS) -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 CC_FLAGS and -include $(OBJFILES:.o=.d) to the end of the makefile body:

CC_FLAGS += -MMD
-include $(OBJFILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

这篇关于我可以编译src /中的所有.cpp文件到obj /中的.o,然后链接到./中的二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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