A Simple Makefile Tutorial

Makefiles are a simple way to organize code compilation. This tutorial does not even scratch the surface of what is possible using make, but is intended as a starters guide so that you can quickly and easily create your own makefiles for small to medium-sized projects.

A Simple Example

Let's start off with the following three files, hellomake.c, hellofunc.c, and hellomake.h, which would represent a typical main program, some functional code in a separate file, and an include file, respectively.

hellomake.c hellofunc.c hellomake.h
#include <hellomake.h>

int main() {
// call a function in another file
myPrintHelloMake(); return(0);
}
#include <stdio.h>
#include <hellomake.h> void myPrintHelloMake(void) { printf("Hello makefiles!\n"); return;
}
/*
example include file
*/ void myPrintHelloMake(void);

Normally, you would compile this collection of code by executing the following command:

gcc -o hellomake hellomake.c hellofunc.c -I.

This compiles the two .c files and names the executable hellomake. The -I. is included so that gcc will look in the current directory (.) for the include file hellomake.h. Without a makefile, the typical approach to the test/modify/debug cycle is to use the up arrow in a terminal to go back to your last compile command so you don't have to type it each time, especially once you've added a few more .c files to the mix.

Unfortunately, this approach to compilation has two downfalls. First, if you lose the compile command or switch computers you have to retype it from scratch, which is inefficient at best. Second, if you are only making changes to one .c file, recompiling all of them every time is also time-consuming and inefficient. So, it's time to see what we can do with a makefile.

The simplest makefile you could create would look something like:

Makefile 1

hellomake: hellomake.c hellofunc.c
gcc -o hellomake hellomake.c hellofunc.c -I.

If you put this rule into a file called Makefile or makefile and then type make on the command line it will execute the compile command as you have written it in the makefile. Note that make with no arguments executes the first rule in the file. Furthermore, by putting the list of files on which the command depends on the first line after the :, make knows that the rule hellomake needs to be executed if any of those files change. Immediately, you have solved problem #1 and can avoid using the up arrow repeatedly, looking for your last compile command. However, the system is still not being efficient in terms of compiling only the latest changes.

One very important thing to note is that there is a tab before the gcc command in the makefile. There must be a tab at the beginning of any command, and make will not be happy if it's not there.

In order to be a bit more efficient, let's try the following:

Makefile 2

CC=gcc
CFLAGS=-I. hellomake: hellomake.o hellofunc.o
$(CC) -o hellomake hellomake.o hellofunc.o

So now we've defined some constants CC and CFLAGS. It turns out these are special constants that communicate to make how we want to compile the files hellomake.c and hellofunc.c. In particular, the macro CC is the C compiler to use, and CFLAGS is the list of flags to pass to the compilation command. By putting the object files--hellomake.o and hellofunc.o--in the dependency list and in the rule, make knows it must first compile the .c versions individually, and then build the executable hellomake.

Using this form of makefile is sufficient for most small scale projects. However, there is one thing missing: dependency on the include files. If you were to make a change to hellomake.h, for example, make would not recompile the .c files, even though they needed to be. In order to fix this, we need to tell make that all .c files depend on certain .h files. We can do this by writing a simple rule and adding it to the makefile.

Makefile 3

CC=gcc
CFLAGS=-I.
DEPS = hellomake.h %.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS) hellomake: hellomake.o hellofunc.o
$(CC) -o hellomake hellomake.o hellofunc.o

This addition first creates the macro DEPS, which is the set of .h files on which the .c files depend. Then we define a rule that applies to all files ending in the .o suffix. The rule says that the .o file depends upon the .c version of the file and the .h files included in the DEPS macro. The rule then says that to generate the .o file, make needs to compile the .c file using the compiler defined in the CC macro. The -c flag says to generate the object file, the -o $@ says to put the output of the compilation in the file named on the left side of the :, the $< is the first item in the dependencies list, and the CFLAGS macro is defined as above.

As a final simplification, let's use the special macros $@ and $^, which are the left and right sides of the :, respectively, to make the overall compilation rule more general. In the example below, all of the include files should be listed as part of the macro DEPS, and all of the object files should be listed as part of the macro OBJ.

Makefile 4

CC=gcc
CFLAGS=-I.
DEPS = hellomake.h
OBJ = hellomake.o hellofunc.o %.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS) hellomake: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)

So what if we want to start putting our .h files in an include directory, our source code in a src directory, and some local libraries in a lib directory? Also, can we somehow hide those annoying .o files that hang around all over the place? The answer, of course, is yes. The following makefile defines paths to the include and lib directories, and places the object files in an obj subdirectory within the src directory. It also has a macro defined for any libraries you want to include, such as the math library -lm. This makefile should be located in the src directory. Note that it also includes a rule for cleaning up your source and object directories if you type make clean. The .PHONY rule keeps make from doing something with a file named clean.

Makefile 5

IDIR =../include
CC=gcc
CFLAGS=-I$(IDIR) ODIR=obj
LDIR =../lib LIBS=-lm _DEPS = hellomake.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS)) _OBJ = hellomake.o hellofunc.o
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ)) $(ODIR)/%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS) hellomake: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) .PHONY: clean clean:
rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~

So now you have a perfectly good makefile that you can modify to manage small and medium-sized software projects. You can add multiple rules to a makefile; you can even create rules that call other rules. For more information on makefiles and the make function, check out the GNU Make Manual, which will tell you more than you ever wanted to know (really).

Makefile 简要辅导 【转载】的更多相关文章

  1. makefile 使用【转载】

    该篇文章为转载,是对原作者系列文章的总汇加上标注. 支持原创,请移步陈浩大神博客: http://blog.csdn.net/haoel/article/details/2886 makefile很重 ...

  2. openwrt: Makefile 框架分析[转载]

    openwrt目录结构 上图是openwrt目录结构,其中第一行是原始目录,第二行是编译过程中生成的目录.各目录的作用是: tools - 编译时需要一些工具, tools里包含了获取和编译这些工具的 ...

  3. 【linux】-Makefile简要知识+一个通用Makefile

    目录 Makefile Makefile规则与示例 为什么需要Makefile Makefile样式 先介绍Makefile的两个函数 完善Makefile 通用Makefile的使用 通用的Make ...

  4. InnoDB多版本(MVCC)实现简要分析(转载)

    http://hedengcheng.com/?p=148 基本知识 假设对于多版本(MVCC)的基础知识,有所了解.InnoDB为了实现多版本的一致读,采用的是基于回滚段的协议. 行结构 InnoD ...

  5. u-boot 之配置分析 (2)

    Makefile简要分析所有这些目录的编译连接都是由顶层目录的makefile来确定的. 1.在makefile中有: unconfig: @rm -f $(obj)include/config.h ...

  6. U-BOOT概述及源码分析(一)

    嵌入式Linux系统从软件角度通常可以分为以下4个层次: 引导加载程序 | Linux内核 | 文件系统 | 用户应用程序 嵌入式Linux系统中典型分区结构: 正常启动过程中,Bootloader首 ...

  7. 转载:谈谈Unicode编码,简要解释UCS、UTF、BMP、BOM等名词

    转载: 谈谈Unicode编码,简要解释UCS.UTF.BMP.BOM等名词 这是一篇程序员写给程序员的趣味读物.所谓趣味是指可以比较轻松地了解一些原来不清楚的概念,增进知识,类似于打RPG游戏的升级 ...

  8. 转载-------makefile 使用总结

    转载自:http://www.cnblogs.com/wang_yb/p/3990952.html 1. Makefile 简介 Makefile 是和 make 命令一起配合使用的. 很多大型项目的 ...

  9. 【转载】makefile经典教程

    该篇文章为转载,是对原作者系列文章的总汇加上标注. 支持原创,请移步陈浩大神博客: http://blog.csdn.net/haoel/article/details/2886 makefile很重 ...

随机推荐

  1. SpringCloud入门(八): Zuul 过滤器详解

    Zuul 过滤器 zuul 有四种过滤器类型,分别是: 1.Pre:过滤器在请求被路由之前调用.我们可利用这种过滤器实现身份验证.在集群中选择请求的微服务.记录调试信息等: 2.Routing:过滤器 ...

  2. vulnhub~sunset:dusk1

    晚上闲来无事,准备做个target,结果是各种错误.在睡觉前还是没有顺利的做出来.先将TroubleSHOOTing 总结如下: 在用hydra爆破mysql的时候,发现 'MySql Host is ...

  3. 在函数中修改全局变量的值,需要加global关键字

    一.引用 使用到的全局变量只是作为引用,不在函数中修改它的值的话,不需要加global关键字.如: #! /usr/bin/python a = 1 b = [2, 3] def func(): if ...

  4. 操作系统-1-存储管理之LFU页面置换算法(leetcode460)

    LFU缓存 题目:请你为 最不经常使用(LFU)缓存算法设计并实现数据结构.它应该支持以下操作:get 和 put. get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1 ...

  5. php--一些有用的Laravel辅助函数

    str_start()/str_finish() 将指定值添加到字符串的开头/结尾(当不是以该值开头/结尾时) blank() 判断给定的值是否为「空」 collect() 根据给定的数组创建一个集合 ...

  6. flask-migrate的基本使用

    Flask-migrate 在实际开发环境中,经常会发生数据库修改的行为.一般我们修改数据库不会手动的去修改,而是去修改orm对应的模型, 然后再把模型映射到数据库中.这时候如果有一个工具能专门做这种 ...

  7. 十年测试老鸟告诉你--自动化测试选JAVA还是选Python--写给还在迷茫中的朋友

    一.前言 Python和Java哪个更适合做自动化测试?这是很多测试工程师从功能跨入自动化纠结的问题,今天测试老鸟来带大家详细分析一下!写给还在迷茫中的朋友! 首先可以确认的是提出这个问题的肯定是一个 ...

  8. mysql全文索引浅谈

    原文链接:http://www.cnblogs.com/robertsun/p/5999588.html 对于一些简单的检索可以通过mysql自带的全文索引及 MATCH AGAINST 查询语句实现 ...

  9. Git 常见问题 冲突原因分析及解决方案

    仅结合本人使用场景,方法可能不是最优的 1. 忽略本地修改,强制拉取远程到本地 主要是项目中的文档目录,看的时候可能多了些标注,现在远程文档更新,本地的版本已无用,可以强拉 git fetch --a ...

  10. std::string::copy函数

    size_t copy (char* s, size_t len, size_t pos = 0) const;