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

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

问题描述

我有三个文件: program.c program.h 头。 ^ h

program.c 包括 program.h headers.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.

推荐答案

有趣的,我不知道化妆将缺省使用对源文件的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

(请记住,让需要标签,而不是空间的缩进,所以一定要解决这个复制时)

但是,为了支持更多的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

我试图通过省略类似$(CC)变量,使这个尽可能简单和$(CFLAGS),它们通常在makefile中看到。如果你有兴趣搞清楚了这一点,我希望我已经给你上个好的开始。

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.

下面的Makefile中我喜欢使用的C源。随意使用它:

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程序来自动包含在当前目录中.c和.h文件,当你添加新的code文件到您的目录意的通配符和patsubst功能,你不会有更新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天全站免登陆