您的位置:首页 > 运维架构 > Linux

关于linux中Makefile文件的编写(简单例子)

2011-09-02 11:49 561 查看
首先创建两个.c文件和一个.h文件,这样可以简单的模拟一个项目源文件

file1.c

#include <stdio.h>

#include "file2.h"

int main()

{

printf("print file1");

File2Print();

return 0;

}

file2.h

#ifndef FILE2_H_

#define FILE2_H_

#ifdef __cplusplus

extern "C" {

#endif

void File2Print();

#ifdef __cplusplus

}

#endif

#endif

file2.c

#include "file2.h"

void File2Print()

{

printf("Print file2");

}

然后开始在该源文件存放的地方创建Makefile文件(文件命名可以随意)

helloworld:file1.o file2.o

gcc file1.o file2.o -o helloworld

file1.o:file1.c file2.h

gcc -c file1.c -o file1.o

file2.o:file2.c file2.h

gcc -c file2.c -o file2.o

clean:

rm -rf *.o helloworld

注意:这边所有命令前面空开的地方都是tab键而不能是空格

首先解释下

1、helloworld和clean是我们自己定义的命令,只需要在linux下执行make helloworld/clean就可以执行makefile中自己定义的操作

2、helloworld:file1.o file2.o表示helloworld是依赖于file1.o,file2.o的

makefile进阶

实例:

项目文件:

-rw-r--r-- 1 tgomc tgomc 1144 Oct 9 14:35 Distinguish.cpp

-rw-r--r-- 1 tgomc tgomc 346 Oct 9 14:25 makefile

-rw-r--r-- 1 tgomc tgomc 3131 Oct 9 14:18 Pmap.cpp

-rw-r--r-- 1 tgomc tgomc 672 Oct 9 11:12 Pmap.h

-rw-r--r-- 1 tgomc tgomc 436 Oct 9 11:12 Read.cpp

-rw-r--r-- 1 tgomc tgomc 497 Oct 9 11:12 Read.h

-rw-r--r-- 1 tgomc tgomc 1204 Oct 9 11:12 ReadMe.txt

-rw-r--r-- 1 tgomc tgomc 290 Oct 9 11:12 StdAfx.cpp

-rw-r--r-- 1 tgomc tgomc 746 Oct 9 11:12 StdAfx.h

-rw-r--r-- 1 tgomc tgomc 201 Oct 9 14:37 test.cfg

-rw-r--r-- 1 tgomc tgomc 2712 Oct 9 14:19 Write.cpp

-rw-r--r-- 1 tgomc tgomc 915 Oct 9 11:12 Write.h



makefile内容:

objects=Distinguish.o Pmap.o Write.o

Dis:$(objects)

g++ $(objects) -o Dis

Distinguish.o:Distinguish.cpp Write.h Pmap.h StdAfx.h

g++ -c Distinguish.cpp -o Distinguish.o

Pmap.o:Pmap.cpp Pmap.h Write.h StdAfx.h

g++ -c Pmap.cpp -o Pmap.o

Write.o:Write.cpp Write.h Pmap.h StdAfx.h

g++ -c Write.cpp -o Write.o

clean:

rm Dis $(objects)


make Dis之后的文件目录:

-rwxrwxrwx 1 tgomc tgomc 58658 Oct 9 14:42 Dis

-rw-r--r-- 1 tgomc tgomc 1144 Oct 9 14:35 Distinguish.cpp

-rw-rw-rw- 1 tgomc tgomc 35800 Oct 9 14:42 Distinguish.o

-rw-r--r-- 1 tgomc tgomc 346 Oct 9 14:25 makefile

-rw-r--r-- 1 tgomc tgomc 3131 Oct 9 14:18 Pmap.cpp

-rw-r--r-- 1 tgomc tgomc 672 Oct 9 11:12 Pmap.h

-rw-rw-rw- 1 tgomc tgomc 50768 Oct 9 14:42 Pmap.o

-rw-r--r-- 1 tgomc tgomc 436 Oct 9 11:12 Read.cpp

-rw-r--r-- 1 tgomc tgomc 497 Oct 9 11:12 Read.h

-rw-r--r-- 1 tgomc tgomc 1204 Oct 9 11:12 ReadMe.txt

-rw-r--r-- 1 tgomc tgomc 290 Oct 9 11:12 StdAfx.cpp

-rw-r--r-- 1 tgomc tgomc 746 Oct 9 11:12 StdAfx.h

-rw-r--r-- 1 tgomc tgomc 201 Oct 9 14:37 test.cfg

-rw-r--r-- 1 tgomc tgomc 2712 Oct 9 14:19 Write.cpp

-rw-r--r-- 1 tgomc tgomc 915 Oct 9 11:12 Write.h

-rw-rw-rw- 1 tgomc tgomc 46464 Oct 9 14:42 Write.o



可以运行./Dis执行项目
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: