简单的makefile

时间:2023-03-09 05:53:26
简单的makefile

单一程序

准备一个hello.c

#include <stdio.h>
int main(void)
{
printf("Hello World!\n");
}

gcc hello.c,执行文件名被自动设置成a.out,可用./a.out直接执行,因为这是编译成功的可执行二进制程序

gcc -c hello.c产生目标文件hello.o

gcc -o hello hello.o利用目标文件制作一个名为hello的执行文件

主、子程序链接

准备一个主程序thanks.c,一个子程序thanks_2.c

//thanks.c
#include <stdio.h>
int main(void)
{
printf("Hello World\n");
thanks_2();
}
//thanks_2.c
#include <stdio.h>
void thanks_2(void)
{
printf("Thank you!\n");
}

进行编译与链接

gcc -c thanks.c thanks_2.c制作出两个.o文件

gcc -o thank thanks.o thanks_2.o产生thanks可执行程序

如果以后更新了thanks_2.c文件,只需要重新编译来产生新的thanks_2.o,然后再链接制作出最后的程序即可,不用再编译thanks.c

调用外部函数库

//sin.c
#include <stdio.h>
#include <math.h>
int main(void)
{
float value;
value = sin (3.14 / 2);
printf("%f\n", value);
}

数学函数库使用的是libm.so这个函数库,最好在编译的时候将它包含进去

gcc sin.c -lm -L/lib -L/lib64

-l: 是加入某个函数库的意思

m: 是libm.so这个函数库

由于Linux默认将函数库放置在lib和lib64中,所以不写也没关系

用make进行宏编译

准备4个文件main.c, haha.c, sin_value.c, cos_value.c

//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 );
}
//haha.c
#include <stdio.h>
int haha(char name[15])
{
printf ("\n\nHi, Dear %s, nice to meet you.", name);
}
//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);
}
正常的步骤
gcc -c main.c haha.c sin_value.c cos_value.c
gcc -o main main.o haha.o sin_value.o cos_value.o -lm
./main

使用make

先准备一个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
$make
$make 再一次

make比shell脚本好在:它能主动判断哪一个源代码有修改过,并仅更新该文件

makefile的基本语法和变量

target: target_file1 target_file2 ...
<tab> gcc -o exe_file_name target_file1 target_file2 ...
  • makefile中#代表注释
  • <tab>需要在命令行的第一个字符
  • target与其依赖文件之间要用:分隔

如果想拥有两个以上的操作时,可如此制作makefile文件

main: main.o haha.o sin_value.o cos_value.o
gcc main main.o haha.o sin_value.o cos_value.o -lm
clean:
rm -fv main main.o haha.o sin_value.o cos_value.o test:
$make clean
$make main

再改进一下:

LIBS = -lm
OBJS = main.o haha.o sin_value.o cos_value.o
main: ${OBJS}
gcc -o main ${OBJS} ${LIBS}
clean:
rm -fv main ${OBJS}

变量的基本语法:

  • 变量与变量内容以=分隔,两边允许空格
  • 变量左边不可以有tab, :
  • 变量应该大写
  • 使用方式,以${变量}的形式