一、假设为三方提供库源码和头文件
1.共享库部分
sanf.c
#include <stdio.h>
int a;
void hello(){
printf("TK------_>>>>>this is hello\n");
}
编译:gcc -shared -fPIC -o libsanf.so sanf.c
生成:libsanf.so
2.头文件
sanf.h
extern int a;
extern "C"{
void hello();
}
以上sanf.h和libsanf.so即为第三方给我们提供的可用资源。
二、如何使用
1.编译链接
main.cpp
#include <stdio.h>
#include "sanf.h"
int main(){
a = 1;
printf("TK------->>>>a is %d\n",a);
hello();
return 0;
}
编译:g++ -c main.cpp
g++ -o main main.o -lsanf -L.
结果:可执行文件main
2.运行
./main
TK------->>>>a is 1
TK------_>>>>>this is hello
三、说明函数添加extern "C"原因
1.我们看C语言sanf.c编译的库libsanf.so中hello的符号
readelf -a libsanf.so
47: 00000000000005cc 18 FUNC GLOBAL DEFAULT 11 hello
2.我们看C++语言main.cpp在不添加extern "C"时hello的符号
readelf -a main.o
13: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _Z5hellov
在这种情况下,静态链接时就会找不到符号。
3.C++语言main.cpp在添加extern "C"时hello的符号
readelf -a main.o
13: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND hello
在这种情况下,静态链接时就能找到符号。
原因:
C++语言支持函数多态,导致函数在编译后生成的符号与C不同。