gcc/g++ 选项将所有目标文件放入单独的目录 [英] gcc/g++ option to place all object files into separate directory

查看:32
本文介绍了gcc/g++ 选项将所有目标文件放入单独的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 gcc/g++ 没有将生成的目标文件放入指定目录的选项.

I am wondering why gcc/g++ doesn't have an option to place the generated object files into a specified directory.

例如:

mkdir builddir
mkdir builddir/objdir
cd srcdir

gcc -c file1.c file2.c file3.c **--outdir=**../builddir/objdir

我知道可以通过为编译器提供单独的 -o 选项来实现这一点,例如:

I know that it's possible to achive this with separate -o options given to the compiler, e.g.:

gcc -c file1.c -o ../builddir/objdir/file1.o
gcc -c file2.c -o ../builddir/objdir/file2.o
gcc -c file3.c -o ../builddir/objdir/file3.o

...而且我知道我可以通过 VPATH 和 vpath 指令编写 Makefile 来简化这一点.

... and I know that I can write Makefiles via VPATH and vpath directives to simplify this.

但是在复杂的构建环境中需要做很多工作.

But that's a lot of work in a complex build environment.

我也可以使用

gcc -c file1.c file2.c file3.c

但是当我使用这种方法时,我的 srcdir 之后充满了 .o 垃圾.

But when I use this approach my srcdir is full of .o garbage afterwards.

所以我认为带有 --outdir 语义的选项会非常有用.

So I think that an option with the semantics of --outdir would be very useful.

你有什么看法?

编辑:我们的 Makefile 的编写方式是将 .o 文件实际放入 builddir/obj 中.但我只是想知道是否有更好的方法.

EDIT: our Makefiles are written in such a way that .o files actually placed into builddir/obj. But I am simply wondering if there might be a better approach.

编辑:有几种方法可以将实现所需行为的负担置于构建系统(又名 Make、CMake 等)上.但我认为它们都是针对 gcc(以及其他编译器)弱点的变通方法.

EDIT: There are several approaches which place the burden to achieve the desired behavior to the build system (aka Make, CMake etc.). But I consider them all as being workarounds for a weakness of gcc (and other compilers too).

推荐答案

这是我的一个项目的切碎生成文件,它编译src"中的源代码并将 .o 文件放在目录obj"中.关键是 patsubst() 函数的使用 - 有关详细信息,请参阅 GNU make 手册(这实际上是一本很好的读物):

This is the chopped down makefile for one of my projects, which compiles the sources in 'src' and places the .o files in the directory "obj". The key bit is the the use of the patsubst() function - see the GNU make manual (which is actually a pretty good read) for details:

OUT = lib/alib.a
CC = g++
ODIR = obj
SDIR = src
INC = -Iinc

_OBJS = a_chsrc.o a_csv.o a_enc.o a_env.o a_except.o 
        a_date.o a_range.o a_opsys.o
OBJS = $(patsubst %,$(ODIR)/%,$(_OBJS))


$(ODIR)/%.o: $(SDIR)/%.cpp 
    $(CC) -c $(INC) -o $@ $< $(CFLAGS) 

$(OUT): $(OBJS) 
    ar rvs $(OUT) $^

.PHONY: clean

clean:
    rm -f $(ODIR)/*.o $(OUT)

这篇关于gcc/g++ 选项将所有目标文件放入单独的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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