如何在 Linux 上为 gcc 制作一个简单的 makefile? [英] How do I make a simple makefile for gcc on Linux?

查看:25
本文介绍了如何在 Linux 上为 gcc 制作一个简单的 makefile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文件:program.cprogram.hheaders.h.

I have three files: program.c, program.h and headers.h.

program.c 包括 program.hheaders.h.

我需要使用 gcc 编译器在 Linux 上编译它.我不知道该怎么做.Netbeans 为我创建了一个,但它是空的.

I need to compile this on Linux using gcc compiler. I'm not sure how to do this. Netbeans created one for me, but it's empty.

推荐答案

有趣,我不知道 make 会默认使用 C 编译器给定有关源文件的规则.

Interesting, I didn't know make would default to using the C compiler given rules regarding source files.

无论如何,一个演示简单 Makefile 概念的简单解决方案是:

Anyway, a simple solution that demonstrates simple Makefile concepts would be:

HEADERS = program.h headers.h

default: program

program.o: program.c $(HEADERS)
    gcc -c program.c -o program.o

program: program.o
    gcc program.o -o program

clean:
    -rm -f program.o
    -rm -f program

(记住 make 需要制表符而不是空格缩进,所以复制时一定要修复)

然而,为了支持更多的 C 文件,你必须为每个文件制定新的规则.因此,要改进:

However, to support more C files, you'd have to make new rules for each of them. Thus, to improve:

HEADERS = program.h headers.h
OBJECTS = program.o

default: program

%.o: %.c $(HEADERS)
    gcc -c $< -o $@

program: $(OBJECTS)
    gcc $(OBJECTS) -o $@

clean:
    -rm -f $(OBJECTS)
    -rm -f program

我试图通过省略通常在 makefile 中看到的 $(CC) 和 $(CFLAGS) 等变量来使这尽可能简单.如果您有兴趣弄清楚这一点,我希望我已经为您提供了一个良好的开端.

I tried to make this as simple as possible by omitting variables like $(CC) and $(CFLAGS) that are usually seen in makefiles. If you're interested in figuring that out, I hope I've given you a good start on that.

这是我喜欢用于 C 源代码的 Makefile.随意使用它:

Here's the Makefile I like to use for C source. Feel free to use it:

TARGET = prog
LIBS = -lm
CC = gcc
CFLAGS = -g -Wall

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)

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

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $@

clean:
    -rm -f *.o
    -rm -f $(TARGET)

它使用 make 实用程序的通配符和 patsubst 功能在当前目录中自动包含 .c 和 .h 文件,这意味着当您将新代码文件添加到您的目录时,您将不必更新 Makefile.但是,如果您想更改生成的可执行文件、库或编译器标志的名称,您只需修改变量即可.

It uses the wildcard and patsubst features of the make utility to automatically include .c and .h files in the current directory, meaning when you add new code files to your directory, you won't have to update the Makefile. However, if you want to change the name of the generated executable, libraries, or compiler flags, you can just modify the variables.

无论哪种情况,请不要使用 autoconf.我求你!:)

In either case, don't use autoconf, please. I'm begging you! :)

这篇关于如何在 Linux 上为 gcc 制作一个简单的 makefile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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