在 C 语言代码工程中经常会用到其他高级语言生成的动态、静态库函数,对于这种情况就需要进行特别处理。本文针对 C++ 实现的一系列库函数在 C 语言代码中的调用方式进行研究说明。
Linux 平台
首先,需要在库函数的头文件中使用 extern C 进行函数声明,使得 C 语言在包含头文件的时候也能够获得函数声明。具体如下:
自定义实现一个 C++ 打印函数,源代码:
#include "myprint.h"
#include <iostream>
void myprint(char *buf)
{
if(!buf)
{
return;
}
std::cout << "MY print:" << buf << std::endl;
}
这个源代码和普通的 C++ 代码没有什么区别,但是头文件中需要添加一些针对 C 语言的声明,具体如下:
#ifndef __MYPRINT_H
#define __MYPRINT_H
#ifdef __cplusplus
extern "C"{
#endif
void myprint(char *buf);
#ifdef __cplusplus
}
#endif
#endif
可以看到,我们在函数头文件声明时专门声明了该函数的 C 语言函数声明。然后调用 g++ 进行库函数编译,针对 C++ 的库的制作一定要使用 g++,使用 gcc 是会报错的。具体如下:
$ g++ myprint.cc -shared -o libmyprint.so -fPIC -Xlinker -rpath=./
这样就已经生成了一个动态库 libmyprint.so ,然后我们编写一个简单的 C 测试代码来调用试一下:
#include <stdio.h>
#include "myprint.h"
int main()
{
printf("test begin:\n");
myprint("hello world!");
printf("test end\n");
return 0;
}
在编译测试程序时主要添加链接库的参数。如下:
gcc test.c -o test -lmyprint -L./ -I. -Xlinker -rpath=./
注意一定要加入后面两个参数,则表示传递给编译器连接库指定的加载目录,使得gcc能够加载 C++ 的动态库。
最终测试结果:
$ ./test
test begin:
MY print:hello world!
test end
Windows 平台
【待添加】
|