本例子摘自《鸟哥的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.c
1 #include <stdio.h>
2 #define pi 3.14159
3 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.c
1 #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.c
1 #include <stdio.h>
2 #include <math.h>
3 #define pi 3.14159
4
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.c
1 #include <stdio.h>
2 #include <math.h>
3
4 #define pi 3.14159
5 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