简体   繁体   English

如何使用GNU make将多个不相关的源文件编译成多个不相关的目标文件?

[英]How can I use GNU make to compile multiple nonrelated source files into multiple nonrelated object files?

I have been learning about gnu make and Makefiles. 我一直在学习gnu make和Makefiles。 Makefiles have make my life easier when I'm working with many dependent object, header and source files. 当我处理许多相关的对象,标头和源文件时,Makefile使我的生活更轻松。 I've heard that make can be used to do all kinds of automation-magic so I'm curious know whether I can use it to compile unrelated files with unrelated main functions into unrelated object files and that all in the same dir. 我听说make可以用于进行各种自动化魔术操作,所以我很好奇我是否可以使用它将具有不相关主要功能的不相关文件编译为不相关的目标文件,并且它们都位于同一目录中。

Here's some code that should do what I want: 这是一些应该执行我想要的代码:

CC=gcc
CFLAGS=-g -Wall -std=gnu99 -DNDEBUG
all:
    $(CC) $(CFLAGS) file1.c -o file1
    $(CC) $(CFLAGS) file2.c -o file2
    $(CC) $(CFLAGS) file3.c -o file3
    $(CC) $(CFLAGS) file4.c -o file4
    etc...

I know how to make a list of *.c files and then the corresponding object files is done like so: 我知道如何制作一个* .c文件列表,然后完成相应的目标文件,如下所示:

TARGET=$(wildcat *.c)
OBJECTS=$(patsubst %.c,%,$(SOURCES))

But that only gives me a list of files respectively. 但这仅分别给了我一个文件列表。 How can I work with individual files within that list so that I can compile one file at a time? 如何使用该列表中的单个文件,以便一次可以编译一个文件?

All figured out, thank you all for your inputs. 大家都想通了,谢谢大家的投入。 Here's one simple solution which does exactly what I was looking for: 这是一个简单的解决方案,完全可以满足我的需求:

SOURCES=$(wildcard *.c)
OBJECTS=$(patsubst %.c,%,$(SOURCES))
all: $(OBJECTS)

Make is a so-called rule-based expert system. Make是所谓的基于规则的专家系统。 You give it the rules for determining dependencies and what to do for each step (There are already many generic pattterns you can override predefined), give it a target, and make determines how to get there and what all to (re-)execute. 您为它提供了确定依赖关系的规则以及每个步骤的操作(已经有很多通用模式可以覆盖预定义),为其指定目标,并由make确定如何到达那里以及(重新)执行所有操作。

Nobody stops you from giving make an explicit target, instead of letting it do the default one (normally the first in your makefile). 没有人阻止您提供明确的目标,而不是让它执行默认目标(通常是makefile中的第一个目标)。

Override dependencies this way: 这样覆盖依赖项:

all: file1 file2 file3

In fact, the rule for making *.o files from the corresponding *.c files is part of the built-in rule set for make: call $(CC) -c on the c file. 实际上,从相应的* .c文件中生成* .o文件的规则是make内置规则集的一部分:在c文件中调用$(CC)-c。 That is, for that task you don't even need a Makefile, much less list the single sources in it. 也就是说, 对于该任务,您甚至不需要Makefile,更不用说列出其中的单个源了。 Just say "make whatevername.o". 只需说“ make whatname.o”即可。

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

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