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

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

问题描述

我有一个C库,我需要在C ++代码中使用,所以我需要包装整个lib与 externC块。问题是,库似乎包含一个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。

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


$ b b

但是,当我在 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 头文件中应用 externC

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

编辑

这不是一个问题使用 externC,这是一个问题链接编译的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++.

already_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.

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

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