C++调用C:
//xxx.c
#include <stdio.h>
void hello()
{
printf("hello\n");
} 编译:gcc
-shared -fPIC -o libhello.so hello.c
cp libhello.so /lib/
调用:
// xxx.cpp
#include <iostream>
#ifdef __cplusplus
extern "C" { // 告诉编译器下列代码要以C链接约定的模式进行链接
#endif
void hello();
#ifdef __cplusplus
}
#endif
int main()
{
hello();
return 0;
} C调C++:// xxx.cpp
#include <iostream>
void world()
{
std::cout << "world" << std::endl;
} 编译: g++ -shared -fPIC -o
libworld.so world.cppcp libhello.so /lib/
做一个中间接口库,对C++库进行二次封装:
#include <iostream>
void world();
#ifdef __cplusplus
extern "C" { // 即使这是一个C++程序,下列这个函数的实现也要以C约定的风格来搞!
#endif
void m_world()
{
world();
}
#ifdef __cplusplus
}
#endif 编译:g++
-shared -fPIC -o libmid.so mid.cpp -lworld
cp libmid.so /lib/
// xxx.c
#include <stdio.h>
int main()
{
m_world();
return 0;
}
本文详细介绍了如何使用C++调用C语言编写的函数,并反过来从C语言环境中调用C++函数的方法。此外,还提供了一个通过创建中间接口库来封装C++库并供C程序调用的具体示例。
906

被折叠的 条评论
为什么被折叠?



