目录
0背景
现在有main.c、hello.c、hello.h、jisuan.c、jisuan.h需要将它们生成可执行文件
//main.c
//代码如下:
#include<stdio.h>
#include"hello.h"
#include"jisuan.h"
void main()
{
printf("hello world\n");
sayhello();
printf("\n输入要的计算数。\n");
double a=0.0,b=0.0,c=0.0,d=0.0;
scanf(“%lf,%lf”,&a,&b);
c=jiafa(a,b);
printf("这两个数的和为:%lf\n",c);
printf("这两个数的积为:%lf\n",d);
}
//hello.c
//代码如下:
#include<stdio.h>
#include"hello.h"
void sayhello()
{
printf("hello,do you want to eat shi!");
}
//hello.h
//代码如下:
#ifndef _HELLO_H_
#define _HELLO_H_
#include<stdio.h>
void sayhello();
#endif
//jisuan.c
//代码如下:
#include"jisuan.h"
double jiafa(double a,double b)
{
return a+b;
}
double jianfa(double a,double b)
{
return a-b;
}
//jisuan.h
//代码如下:
#ifndef _JISUAN_H_
#define _JISUAN_H_
#include<stdio.h>
#include<math.h>
double jiafa(double a,double b);
double jianfa(double a,double b);
double chengfa(double a,double b);
#endif
1.makedile编译
1.1基础方法
新建一个makefile 代码如下:
testone:main.o jisuan.o hello.o
icc main.o jisuan.o hello.o -o main
main.o:main.c jisuan.h hello.h
icc -c main.c
jisuan.o:jisuna.c jisuna.h
icc -c jisuan.c
hello.o:hello.c hello.h
icc -c hello.c
clean:
rm -f *.o
1.2多文件简易方法
makefile 代码如下:
file=*.c
CC=icc
all:$(file)
${CC} -o main $(file)
clean:
rm -f *.o main
2.生成静态/动态连接库
静态连接库以 .a 为后缀,动态链接库以 .so 结尾
2.1静态库
2.1.1静态库生成
生成静态库的名称前三个字符必须是lib。makefile如下:
icc -c hello.c
icc -c jisuan.c
ar crv libtest.a hello.o jisuan.o
多个 *.c 文件生成静态库时可以进行以下方式:
file=*.c
FIN=icc
all:$(file)
${FIN} -c $(file)
ar -rv libtest.a *.o
rm -f *.o
clean:
rm -f *.a
icc是编译器,也可用gcc,g++。
2.1.2静态库链接
①icc -o main main.c -L. -ltest
②icc main.c libtest.a -o main
③先生成main.o
icc -c main.c
生成可执行文件
icc -o main main.o libtest.a
上述三种方法均可。
2.2动态库
2.2.1动态库生成
生成动态库的名称前三个字符必须是lib,以 .so 为后缀名。makefile如下:
icc c hello.c
icc c jisuan.c
icc -shared -fPIC -o libtest.so hello.o jisuan.o
#shared:表示指定生成动态链接库,不可省略
#-fPIC:表示编译为位置独立的代码,不可省略
多个 *.c 文件生成动态库时可以进行以下方式:
file=*.c
FIN=icc
all:$(file)
${FIN} -c $(file)
${FIN} -shared -fPIC -o libtest.a *.o
rm -f *.o
clean:
rm -f *.so
icc是编译器,也可用gcc,g++。
2.2.2动态库链接
①icc -o main main.c -L. -ltest
②icc main.c libtest.so -o main
上述两种方法均可。