- 论坛徽章:
- 0
|
用一个例子来说明如何编写makefile.
程序源代码:
//file: a.h
#ifndef a_h
#define a_h
class A {
public:
A();
~A();
void f();
};
#endif //a_h
//file: a.cpp
#include "a.h"
A::A(){
}
A::~(){
}
void A::f(){
}
//file: b.h
#ifndef b_h
#define b_h
class B{
public:
B();
~();
void g();
};
#endif //b_h
//file: b.cpp
#include "b.h"
B::B(){
}
B::~B(){
}
void B::g(){
}
//file: main.cpp
#include "a.h"
#include "b.h"
int main()
{
A a;
B b;
b.g();
return 0;
}
上面源程序的组织形式应该是最常见的一种了。那么现在要编写
一个makefile文件,让编译器自动地进行编译。
首先,makefile文件就是由一条一条的目标依赖命令组成的,
通常一条这样的命令分成两行来写,第二行通常
是编译连接命令。并且要行首以键开头,紧接着命令。
make程序将一条一条的执行这些命令。
其次,目标依赖命令的形式是
target : dependencies
command args
现在要搞清楚,用什么编译命令。由于是在unix/linux上,
所以自然应该是cc/gcc/g++了。
还要清楚一点:最后的可执行目标程序是由所有的.cpp文件
经过编译后的.o文件一起构成的。
好了,现在开始编写makefile文件了。
我们假定最后生成的可执行目标名称是exam。
#comment , start with #(sharp)
exam : main.o a.o b.o
g++ main.o a.o b.o -o exam
main.o : main.cpp a.h b.h
g++ -c main.cpp -o main.o
a.o : a.cpp a.h
g++ -c a.cpp -o a.o
b.o : b.cpp b.h
g++ -c b.cpp -o b.o
#makefile end
请注意每个命令都是以键开始的。
写好后,放到源文件所在目录。
然后运行
$ make
就会看到你用到的编译命令行了。
当然可以在makefile文件中使用宏变量。这样至少书写的时候方便一点。
先介绍三个特殊的预定义的宏变量。
$@ 指代当前的目标名称(target)
$^ 指代当前整个的依赖文件列表(dependencies)
$
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/33043/showart_316324.html |
|