用extern&"C&"包装C库除了内部C ++ include [英] Wrapping a C lib with extern "C" except an internal C++ include

查看:42
本文介绍了用extern&"C&"包装C库除了内部C ++ include的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C库,需要在C ++代码中使用,因此我需要用 extern"C" 块包装整个lib.问题在于该库似乎包含一个C ++编译代码,因此包装整个lib也会包装该C ++头文件.

I have a C library that I need to use in a C++ code, so I need to wrap the whole lib with an extern "C" block. The problem is that the library seems to include a C++ compiled code, so wrapping the whole lib would also wrap that C++ header.

lib.h 内部,我只包含要公开的所有内部标头,如下所示:

Inside lib.h I only include all the internal headers I want to expose, something like this:

#ifndef LIB_H
#define LIB_H

#include "lib_foo.h"
#include "lib_bar.h"
#include "lib_baz.h"

#endif

因此客户端只需要包含 lib.h 即可使用该库.

So the client will only need to include lib.h to use the lib.

在我的第一次尝试中,这样做是

In my first attempt I've done this:

#ifndef LIB_H
#define LIB_H

extern "C" {
  #include "lib_foo.h"
  #include "lib_bar.h"
  #include "lib_baz.h"
}

#endif

但是当我在 already_compiled_c ++.h 内部执行任何函数时,我得到了符号查找错误.

But then I get a symbol lookup error when I execute any function inside already_compiled_c++.h.

如何避免在 already_compiled_c ++.h 头文件中应用 extern"C" ?

How can I avoid from applying extern "C" in the already_compiled_c++.h header file?

已解决.这不是使用 extern"C" 的问题,而是将已编译的c ++库与gyp正确链接的问题:

Solved. This was not a problem using extern "C", it was a problem linking the compiled c++ library with gyp correctly: Using shared library in Gyp in node-sqlite3

推荐答案

请注意, extern C 不是合法的C,因此只有在编译为C ++时才应包括在内.

Note that extern C isn't legal C, so it must only be included hen compiling as C++.

已经_compiled_c ++.h标头可能包含防止多个包含的防护措施,因此请首先包含它:

The already_compiled_c++.h header probably contains a guard against multiple includes, so just include it first:

#ifndef LIB_H
#define LIB_H

# This include added so that it won't get marked extern "C" when included by lob_foo.h.
#include <already_compiled_c++.h>

#ifdef __cplusplus
extern "C" {
#endif

  #include "lib_foo.h"
  #include "lib_bar.h"
  #include "lib_baz.h"

#ifdef __cplusplus
}
#endif

#endif

注意:您需要检查是否有条件包括了 already_compiled_c ++.h 并添加了相应的条件.

Note: You need to check if already_compiled_c++.h is conditionally included and add the corresponding conditionals.

这篇关于用extern&amp;"C&amp;"包装C库除了内部C ++ include的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆