我正在编写一个需要使用特定 api 的 C 程序(myapp); api 是用 C++ 编写的。我使用过 C 和 C++,但从来没有同时使用过,而且我很困惑。

因此,api 提供了以下目录,我将其放置在名为 include 的文件夹中,与我的 makefile 处于同一级别:

libmyapi.a
api/api.h

我的主要源文件是 src/myapp.c,它包含使用 #include "api/api.h" 的 api。

我的 make 命令是(加上一些标志,我没有列出,因为我认为它们在这里不相关):
gcc  -Linclude -lmyapi -Iinclude  src/myapp.c -o lib/myapp.sp -lrt

我遇到的问题是 api.h 文件包含对命名空间等的引用。例如,在某一时刻它具有:
namespace MyAPI {
  namespace API {
    typedef SimpleProxyServer SimpleConnection;
  }
}

显然 C 编译器不知道这意味着什么。

所以,我假设我需要使用 C++ 编译器进行编译,但后来有人说我没有,我可以将代码“包装”在“extern 'C'”中,但我真的不明白。在线阅读后,我不再继续。

我是否需要用 C++ 编译(即使用 g++)?

我是否需要“包装”代码,这是什么意思?我只是做
#ifdef __cplusplus
  extern "C" {
    namespace MyAPI {
      namespace API {
        typedef SimpleProxyServer SimpleConnection;
      }
    }
  }
#endif

还是我只是把线包起来
namespace MyAPI {
      namespace API {

然后他们对应的}}?

头文件调用其他头文件,因此我可能需要在很多地方执行此操作。

到目前为止,我已经尝试了所有变体,但都出现了错误和警告,但是我不知道我是在做包装错误,设置g++编译器标志错误,使用错误的编译器还是执行其他操作!如果我知道要使用的方法,则至少可以开始调试。谢谢!

最佳答案

您可以编写一个小的C++程序来为API创建C绑定(bind)。

提供以下API:

namespace MyAPI {
  namespace API {
    typedef SimpleProxyServer SimpleConnection;
  }
}

您可以创建c_api.h
#ifdef __cplusplus
extern "C" {
#endif

struct api_handle_t;
typedef struct api_handle_t* api_handle;
api_handle myapi_api_create();
void myapi_api_some_function_using_api(api_handle h);
void myapi_api_destroy(api_handle h);

#ifdef __cplusplus
}
#endif

和c_api.cpp
#include "c_api.h"
#include <myapi/api/stuff.hpp>

struct api_handle_t
{
    MyAPI::API::SimpleConnection c;
};

api_handle myapi_api_create()
{
    return new api_handle_t;
}

void myapi_api_some_function_using_api(api_handle h)
{
    //implement using h
}

void myapi_api_destroy(api_handle h)
{
    delete h;
}

使用C++编译器进行编译,并将c_api.h文件包含在C项目中,并链接到使用C++编译器创建的库和原始库。

10-04 20:56
查看更多