文件类型介绍:
- .o是编译中间目标文件,相当于windows上的.obj文件,不可执行
- .out是可执行文件,相当于windows上的exe文件,可直接执行
- .so是共享库,用于动态链接,相当于windows上.dll文件
- .a是静态库,由多个.o练链接得到,用于静态链接编译
#include<iostream>
using namespace std;
int main(){
cout<<"Hello World"<<endl;
return 0;
}
生成.out文件
-
命令gcc test.c
-
这是默认生成.out文件,使用./a.out表示在当前目录下执行a.out文件,打印出hello world结果。
-
如果要自定义生成.out文件名,可以使用如下命令
gcc test.c -o test.out
生成.o文件
- 首先创建hello.c文件
#include<stdio.h>
void hello(){
printf("hello world\n");
}
- 使用命令创建hello.o文件 gcc -c hello.c
.o文件作为中间文件,无法直接执行,但可以作为创建静态库文件的一部分
生成.a文件
- ar -cr libhello.a hello.o
- .a文件名开头是lib表示动态库
- 修改test.c内容如下:
#include<stdio.h>
int main(){
void hello();
printf("<<hello world>>\n");
hello();
return 0;
}
- 编译test.c,静态链接libhello.a:
- gcc test.c libhello.a -o test.out
生成共享库 .so文件
- 首先要生成.o文件,于是使用命令gcc -c -fPIC hello.c编译出.o文件(-fPIC选项是什么?),hello.c就是上面出现过的。然后才去生成.so文件
- 命令:gcc -shared -fPIC -o libhello2.so hello.o
- 然后将libhello2.so文件与test.c文件编译生成test2.out执行文件
- 命令:gcc -o test2.out test.c -L. -lhello2 (-lhello2与libhello2后面的hello2对应)
但是在调用test.out的时候报错了。
- 报错是因为找不到动态库文件libhello2.so。程序在运行时,会在/usr/lib和/lib等目录中查找需要的动态库文件。(动态编译与静态编译的区别)
- 若找到,则载入动态库,否则将提示类似上述错误而终止程序运行。
- 我们将文件libhello2.so移动到目录/usr/lib中,再运行test.out,成功
同样,g++编译也是相似的。