具有多个可执行文件的 Makefile [英] A Makefile with Multiple Executables

查看:33
本文介绍了具有多个可执行文件的 Makefile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 makefile,它使用宏一次从多个文件创建多个可执行文件.我尝试搜索以前回答过的问题,但由于我对 C 编程以及使用 gcc 相当陌生,所以我无法找到我的问题的答案.

I am trying to write a makefile which uses macros to create multiple executables from multiple files at once. I tried searching through previously answered questions but, because I am fairly new to programming in C as well as working with gcc, I was not able to find an answer to my question.

这是我目前所拥有的:

CC=gcc
CFLAGS=-I.
OBJ = ex1.c ex3.c
EXECUTABLE = ex1 ex3

$(EXECUTABLE): $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

clean:
    rm -f $(EXECUTABLE)

我想要这条线

$(EXECUTABLE): $(OBJ)

分别从文件 ex1.c ex3.c 创建可执行文件 ex1 和 ex3.

to create executables ex1 and ex3 from files ex1.c ex3.c respectively.

推荐答案

对于这种特殊情况,每个可执行文件都有一个带有 .c 扩展名的源文件,您只需要一行 Makefile:

For this particular case, where each executable has a single source file with .c extension, all you need is a one line Makefile:

all: ex1 ex3

make 的内置默认规则已经可以工作了:

The built-in default rules for make then work already:

$ make
cc -O2 -pipe   ex1.c  -o ex1
cc -O2 -pipe   ex3.c  -o ex3

在幕后,make 正在使用 POSIX 强制的内置单后缀规则

.c:
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $<

使用 make CC=gcc CFLAGS=-O2 LDFLAGS=-s 和类似命令根据自己的喜好改变命令.

Vary the command to your liking with make CC=gcc CFLAGS=-O2 LDFLAGS=-s and similar.

今日花絮:事实上,如果您愿意在调用 make 时命名目标,您可以使用一个空的,甚至运行没有任何生成文件:

Trivia of the day: in fact, if you are willing to name the targets when invoking make, you can use an empty or even run without any Makefile:

$ make -f /dev/null CC=gcc CFLAGS=-O2 LDFLAGS=-s ex1 ex3
gcc -O2 -s ex1.c  -o ex1
gcc -O2 -s ex3.c  -o ex3
$ rm -f Makefile ex1 ex3
$ make CC=gcc CFLAGS=-O2 LDFLAGS=-s ex1 ex3
gcc -O2 -s ex1.c  -o ex1
gcc -O2 -s ex3.c  -o ex3

变魔术!

根据经验,不要重新发明轮子(或规则),使用已经存在的规则.它大大简化了您的生活.这使得小而性感的 makefile 给女士们留下深刻印象:-)

As a rule of thumb, don't reinvent the wheel (or rules), use the rules that are already there. It simplifies your and make's life a lot. This makes for small and sexy makefiles to impress the ladies with :-)

这篇关于具有多个可执行文件的 Makefile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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