Linux实验课二(重点:动态链接库,makefile使用)
编写包含多文件的.c源码
1、编写包含多文件的.c源码,通过调用自定义函数,实现功能:用户输入一个数字,程序计算并输出介于1至此数之间所有个位数为1的素数;如果不存在,则打印-1
shiyan1.c
#include<stdio.h>
#include"zhishu.h"int main(int argc,char const *argv[])
{int num;printf("plese input");scanf("%d",&num);if(num<11)printf("fuhe fanwei yaoqiu zhishu ");else{for(int i =11;i<num;i++){if(iszhishu(i))printf("%d\n",i);}}return 0;
}
zhishu.c
#include "zhishu.h"
bool iszhishu(int num)
{int sqrtm =(int )sqrt(num);for(int i=2;i<=sqrtm;i++){if(num%i==0)return false;if(num%10!=1)return false;}return true;
}
zhishu.h
#include<stdbool.h>
#include<math.h>
bool iszhishu(int num);
2、直接使用gcc编译多个源文件并运行结果。
3、通过创建动态链接库lib***.so,使得 main 函数调用自定义函数时,可使用动态链接库,编译生成运行结果。
相关学习推荐文章Linux环境下创建并使用动静态库(动态链接与静态链接)_linux链接静态库-CSDN博客
创建.o文件:gcc -fPIC -o hello.o -c hello.c
这里里新增了 -fPIC 选项,实际上改变的是 hello.o 的符号表,我们可以使用 nm 命令查看hello.o的符号表,多出了一个全局偏移表,没有这个偏移表是无法动态编译的。
4、编写Makefile文件,使用make编译并运行。
相关资料学习文章:从0开始教你编写Makefile文件-CSDN博客
stpe1:建立需要的文件
我们这次实验用到shiyan1.c zhishu.c zhishu.h,文件里的内容与上面相同
检查zhishu.c
中是否包含#include <math.h>
头文件声明
step2:创建makefile文件
vi makefile,在makefile文件中编写如下内容
shiyan1:shiyan1.o zhishu.ogcc -o shiyan1 shiyan1.o zhishu.o -lm
shiyan1.o:shiyan1.cgcc -c shiyan1.c
zhishu.o:zhishu.cgcc -c zhishu.c
clear:rm *.o shiyan1
在gcc -o shiyan1 shiyan1.o zhishu.o 后面不加 -lm就会报错如下
gcc -c shiyan1.c
gcc -c zhishu.c
gcc -o shiyan1 shiyan1.o zhishu.o
zhishu.o: In function `iszhishu':
zhishu.c:(.text+0x11): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: shiyan1] Error 1
该错误是由于链接阶段未能正确链接数学库(libm
)导致的。sqrt
函数属于数学库,需在编译时通过-lm
选项显式链接
step3:make
在make之后没有报错就可以直接可以运行shiyan1