简体   繁体   English

如何在makefile指令中同时包含C和C ++文件

[英]How to include both C and C++ files in makefile directives

The following part is commonly found in makefiles. 以下部分通常在makefile中找到。

OBJS := $(SRCS:%.c=$(OBJDIR)/%.o)

$(OBJDIR)/%.o : %.c
    $(CC) $(DEFS) $(CFLAGS) -o$@ $<

Now my source folder contains both C and C++ files, and I want to link all object files created together using g++. 现在,我的源文件夹同时包含C和C ++文件,我想链接使用g ++创建的所有目标文件。 But how do I specify to also also include *.cpp files to get compiled. 但是我如何指定还包括* .cpp文件进行编译。 I mean how do I modify OBJS to also include *.cpp files. 我的意思是我如何修改OBJS以也包括* .cpp文件。

For OBJDIR, maybe, I can do the C++ equivalent like this. 对于OBJDIR,也许我可以像这样做C ++。 I guess the makefile would guess correctly when to use CXX (g++ for C++ files) and when to use CC (gcc for C files). 我猜想makefile会正确猜测何时使用CXX(对于C ++文件为g ++)和何时使用CC(对于C文件为gcc)。

$(OBJDIR)/%.o : %.cpp
        $(CXX) $(DEFS) $(CFLAGS) -o$@ $<

But then, how do I add this rule to OBJS? 但是,如何将这个规则添加到OBJS?

You want to use: 您要使用:

OBJS := $(addsuffix .o,$(basename $(SRCS)))

then add your pattern rule for building .o from .cpp (unless, as mentioned here, you can just use the built-in rules). 然后添加用于从.cpp构建.o模式规则(除非,如此处所述,您只能使用内置规则)。

The above strips off the suffix, regardless of what it is, then adds .o to the end. 上面的代码去除了后缀,不管它是什么,然后在末尾添加.o

You may not need a rule for building .o files from corresponding .cpp or .c files at all, as Make comes with default rules for that, and those look a lot like what you present. 您可能根本不需要从相应的.cpp或.c文件构建.o文件的规则,因为Make带有默认规则,而这些规则看起来很像您呈现的内容。 The key is probably to specify which .o files need to be built in the first place. 关键可能是要指定首先要构建哪些.o文件。

I often see that approached by classifying the C sources separately from the C++ sources. 我经常看到通过将C源代码与C ++源代码分开来实现这一点。 Then you might have something like this: 然后,您可能会遇到以下情况:

C_SRCS = ...
CPP_SRCS = ...

OBJS = $(C_SRCS:.c=.o) $(CPP_SRCS:.cpp=.o)

all: myprog

myprog: $(OBJS)
    $(CXX) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)

If you do need your own rules for building .o files from sources, then you could of course add those. 如果您确实需要自己的规则来从源代码构建.o文件,那么您当然可以添加这些规则。

Note also that the above has no dependencies on GNU make extensions, and if that's important to you then you'll want to avoid GNU style pattern rules for building the object files. 还要注意,以上内容对GNU make扩展没有依赖性,如果这对您很重要,那么您将需要避免使用GNU样式模式规则来构建目标文件。 That's what traditional suffix rules are for. 这就是传统的后缀规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM