makefile就像一個(gè)Bash腳本,其中也可以執(zhí)行操作系統(tǒng)的命令。makefile帶來(lái)的好處就是——“自動(dòng)化編譯”,一旦寫好,只需要一個(gè)make命令,整個(gè)工程完全自動(dòng)編譯,極大的提高了軟件開(kāi)發(fā)的效率。
1 例子源碼 sin_value.c
#include <stdio.h>
#include <math.h>
#define pi 3.14159
float angle;
void sin_value(void)
{
float value;
value = sin ( angle / 180. * pi );
printf ("\nThe Sin is: %5.2f\n",value);
}
cos_value.c
#include <stdio.h>
#include <math.h>
#define pi 3.14159
float angle;
void cos_value(void)
{
float value;
value = cos ( angle / 180. * pi );
printf ("The Cos is: %5.2f\n",value);
}
haha.c
#include <stdio.h>
int haha(char name[15])
{
printf ("\n\nHi, Dear %s, nice to meet you.", name);
}
main.c
#include <stdio.h>
#define pi 3.14159
char name[15];
float angle;
int main(void)
{
printf ("\n\nPlease input your name: ");
scanf ("%s", &name );
printf ("\nPlease enter the degree angle (ex> 90): " );
scanf ("%f", &angle );
haha( name );
sin_value( angle );
cos_value( angle );
}
分析4個(gè)源文件,main.c需要使用另外3個(gè)文件中的函數(shù),并且函數(shù)文件又用到了math庫(kù)。
2 手動(dòng)逐一操作 下面先用gcc進(jìn)行編譯鏈接執(zhí)行:
1 編譯4個(gè).c源文件,生成對(duì)應(yīng)的.o目標(biāo)文件。
gcc -c main.c haha.c sin_value.c cos_value.c
2 再進(jìn)行鏈接,注意添加庫(kù)目錄。
gcc -o main main.o haha.o sin_value.o cos_value.o -lm -L/usr/lib -L/lib
3 測(cè)試。
./main
Please input your name: xxpcb
Please enter the degree angle (ex> 90): 30
Hi, Dear xxpcb, nice to meet you.
The Sin is: 0.50
The Cos is: 0.87
3 使用makefile 3.1 創(chuàng)建一個(gè)makefile vim makefile,文件并編輯如下:
main: main.o haha.o sin_value.o cos_value.o
gcc -o main main.o haha.o sin_value.o cos_value.o -lm
注意:第2行的開(kāi)頭的空格是鍵。
3.2 使用編解的makefile進(jìn)行自動(dòng)編譯 編譯器前先清除之前生成的文件,再使用make命令編譯:
rm -f main *.o
make
此時(shí)已經(jīng)生成生成完畢了。
3.3 嘗試再次使用make編譯 查看效果:
make
make: 'main' is up to date.
可以看到,由于程序沒(méi)有修改過(guò),因而沒(méi)有重新編譯,只是進(jìn)行更新操作。
4 完善makefile 4.1 添加clean功能
main: main.o haha.o sin_value.o cos_value.o
gcc -o main main.o haha.o sin_value.o cos_value.o -lm
clean:
rm -f main main.o haha.o sin_value.o cos_value.
c
cc -c -o cos_value.o cos_value.c
gcc -o main main.o haha.o sin_value.o cos_value.o -lm
4.2 使用變量簡(jiǎn)化makefile
LIBS = -lm
OBJS = main.o haha.o sin_value.o cos_value.o
main: ${OBJS}
gcc -o $@ ${OBJS} ${LIBS}
clean:
rm -f main ${OBJS}
注意:makefile中的變量與bash中的變量,語(yǔ)法稍有不同,makefile變量的基本語(yǔ)法為:
4.3 關(guān)于CFLAGS 命令行時(shí)輸入
例如:
CFLAGS="-Wall" make clean main
LIBS = -lm
OBJS = main.o haha.o sin_value.o cos_value.o
CFLAGS="-Wall"
main: ${OBJS}
gcc -o $@ ${OBJS} ${LIBS}
clean:
rm -f main ${OBJS}
- 使用shell默認(rèn)的環(huán)境變量
命令行中指定的CFLAGS優(yōu)先級(jí)最高,然后是makefile文件中指明的CFLAGS,如果前兩種都未指明CFLAGS,則使用shell默認(rèn)的環(huán)境變量。
參考:《鳥哥的Linux私房菜 (基礎(chǔ)學(xué)習(xí)篇 第三版)》 來(lái)源:https://www./content-3-873051.html
|