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

查看:15
本文介绍了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天全站免登陆