相关疑难解决方法(0)

我可以在C程序中使用C++创建的共享库吗?

我正在使用C创建程序.但是,我需要使用许多只有C++的API.那么,我是否有可能在C++中创建共享对象,然后使用C访问其功能?

  1. 我将传递和返回的唯一数据是C兼容的数据类型.
  2. 转换或迁移到cpp不是一个选项.

如果无法连接这些代码,我如何从C++代码获取信息到C代码?我尝试从C调用C++函数,但是当我包含时,我在链接期间遇到错误<string>.所以当我从C调用C++函数时,我应该只使用那些与C编译器兼容的代码吗?

C++头文件cppfile.hpp

#ifndef CPPFILE_H
#define CPPFILE_H
    #ifdef __cplusplus
    extern "C" {
    #endif

    extern int myfunction(const char *filename);

   #ifdef __cplusplus
   }
   #endif
#endif
Run Code Online (Sandbox Code Playgroud)

C++文件cppfile.cpp

#include "cppfile.hpp"
#include <string>
int myfunction(const char *filename) {
    String S(filename);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

C文件cmain.c

#include "cppfile.hpp"
int main(int argc, char **argv)
{
     int i = myfunction(argv[1]);
     printf("%d\n", i);
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译:

gcc -c cmain.c
g++ -fPIC -shared -o cppfile.so cppfile.cpp
Run Code Online (Sandbox Code Playgroud)

c c++ compilation shared-libraries

29
推荐指数
2
解决办法
2万
查看次数

标签 统计

c ×1

c++ ×1

compilation ×1

shared-libraries ×1