extern c 是c++ 兼容c语言接口的一种方式,关键在于c++支持函数重载,同名的函数参数不通话编译后会产生不同的函数符号,而c语言则没有这个特性
在c++中使用extern "C", 就相当于以C的接口方式导出, 而C是不支持函数重载的;
这样编译的动态库不仅可以给c++程序调用还可以给其他任何语言区调用
去掉 extern"C"之后连也可以编译生成动态库,当c++程序调用这个库的时候没有问题, 但linux下别的语言比如java程序调用这个动态库的函数时, 报: "找不到函数定义"
linux下
test.h
test.cpp
g++ -fPIC -shared test.cpp -olibtest.so
这种方式编译的动态库可以通过其他语言的程序调用
test.h
test.cpp
g++ -fPIC -shared test.cpp -olibtest.so
这种方式编译的接口只能通过c++来调用,java调用的时候会提示add函数找不到
在c++中使用extern "C", 就相当于以C的接口方式导出, 而C是不支持函数重载的;
这样编译的动态库不仅可以给c++程序调用还可以给其他任何语言区调用
去掉 extern"C"之后连也可以编译生成动态库,当c++程序调用这个库的时候没有问题, 但linux下别的语言比如java程序调用这个动态库的函数时, 报: "找不到函数定义"
linux下
test.h
#ifndef TEST_H
#define TEST_H
#ifdef __cplusplus
extern "C"
{
#endif
int add (int a,int b);
#ifdef __cplusplus
}
#endif
#endif
test.cpp
#include "test.h"
int add(int a,int b)
{
return a+b;
}
g++ -fPIC -shared test.cpp -olibtest.so
这种方式编译的动态库可以通过其他语言的程序调用
test.h
#ifndef TEST_H
#define TEST_H
int add (int a,int b);
#endif
test.cpp
#include "test.h"
int add(int a,int b)
{
return a+b;
}
g++ -fPIC -shared test.cpp -olibtest.so
这种方式编译的接口只能通过c++来调用,java调用的时候会提示add函数找不到