?本例子摘自《鳥哥的linux私房菜-基礎學習第四版》
21.3 用make進行宏編譯
書中的代碼在本機器(版本見下)編譯出錯,改正代碼后發布此文章:
#kernel version:
root@localhost:~/testmake# uname -a
Linux localhost 6.12.0-65.el10.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Mar 19 12:37:11 UTC 2025 x86_64 GNU/Linux
#CENT OS distribution:
root@localhost:~/testmake# cat /etc/redhat-release
CentOS Stream release 10 (Coughlan)
先來想象一個案例,假設我的執行檔里面包含了四個原始碼文件,
分別是 main.c haha.c sin_value.c cos_value.c 這四個文件,這四個文件的目的是:
main.c :主要的目的是讓用戶輸入角度數據與呼叫其他三支子程序;
haha.c :輸出一堆有的沒有的訊息而已;
sin_value.c :計算使用者輸入的角度(360) sin 數值;
cos_value.c :計算使用者輸入的角度(360) cos 數值。
root@localhost:~/testmake# cat -n main.c1 #include <stdio.h>2 #define pi 3.141593 char name[15];4 float angle;5 6 7 int haha(char[15]);8 void sin_value(float);9 void cos_value(float);10 11 int main(void)12 {13 printf ("\n\nPlease input your name: ");14 scanf ("%s", &name );15 printf ("\nPlease enter the degree angle (ex> 90): " );16 scanf ("%f", &angle );17 haha( name );18 sin_value( angle );19 cos_value( angle);20 }
root@localhost:~/testmake# cat -n haha.c1 #include <stdio.h>2 int haha(char name[15])3 {4 printf ("\n\nHi, Dear %s, nice to meet you.", name);5 }
root@localhost:~/testmake# cat -n cos_value.c1 #include <stdio.h>2 #include <math.h>3 #define pi 3.141594 5 void cos_value(float angle)6 {7 float value;8 9 value = cos ( angle / 180. * pi );10 printf ("The Cos is: %5.2f\n",value);11 }
root@localhost:~/testmake# cat -n sin_value.c1 #include <stdio.h>2 #include <math.h>3 4 #define pi 3.141595 void sin_value(float angle)6 {7 float value;8 9 value = sin ( angle / 180. * pi );10 printf ("\nThe Sin is: %5.2f\n",value);11 }
#1.先進行目標文件的編譯,最終會有四個 *.o的檔名出現:
root@localhost:~/testmake# gcc -c main.c
root@localhost:~/testmake# gcc -c haha.c
root@localhost:~/testmake# gcc -c sin_value.c
root@localhost:~/testmake# gcc -c cos_value.c#2.再進行連接成為執行檔,并加入libm的數學函式,以產生main執行檔:
root@localhost:~/testmake# gcc -o main main.o haha.o sin_value.o cos_value.o -lm#3.本程序的執行結果,必須輸入姓名,360角度的角度值來計算:
root@localhost:~/testmake# ./main#3.1 輸入姓名
Please input your name: TT
#3.2 輸入以360角度為主的角度
Please enter the degree angle (ex> 90): 30#3.3 這三行為輸出結果哦!
Hi, Dear TT, nice to meet you.
The Sin is: 0.50
The Cos is: 0.87#4 查看文件類型
root@localhost:~/testmake# ls |xargs -n 1 file -i
cos_value.c: text/x-c; charset=us-ascii
cos_value.o: application/x-object; charset=binary
haha.c: text/x-c; charset=us-ascii
haha.o: application/x-object; charset=binary
main: application/x-executable; charset=binary
main.c: text/x-c; charset=us-ascii
main.o: application/x-object; charset=binary
makefile: text/plain; charset=us-ascii
sin_value.c: text/x-c; charset=us-ascii
sin_value.o: application/x-object; charset=binary
sourcetarfile: inode/directory; charset=binary