混合 c 和 c++

发布于 2024-12-25 14:00:50 字数 169 浏览 2 评论 0原文

我有几个关于混合代码的问题:

  1. 一个基于 c 的完整项目,如果我想使用 c++ 库,那么我用纯 c 代码创建一个包装器,然后构建该共享库,我是否必须这样做更改为 g++ 而不是 gcc 编译器?

  2. 如果包装器与库一起编译为静态库怎么办?

I have couple of questions that about mixing code:

  1. a complete project based on c, if I wanna use a c++ library, then I create a wrapper around it with pure c code,then build that shared library, do I have to change to g++ instead of gcc compiler?

  2. what if the wrapper compile as static library with the library?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

带刺的爱情 2025-01-01 14:00:50

我很想知道您使用的是什么库,只有 C++ 版本,而不是纯 C 接口。

无论如何,由于您将调用 C++ 代码,因此您的包装器将被视为 C++,并且需要使用 g++ 进行编译。这与 name-mangling 有关,您需要能够调用这些函数C++ 库公开。您可以使用 readelf -s 查看它们。

但是,您的包装器公开的函数需要标记为 extern "C"这样他们的名字就不会被破坏。然后您将能够从纯 C 应用程序调用它们。

静态与共享库在这里并不重要。只需生成正确的符号即可进行链接。

I'm interested to know what library you're using that has only a C++ version, and not a pure C interface.

Regardless, Since you're going to be calling C++ code, your wrapper will be considered C++ and will need to be compiled with g++. This has to do with name-mangling, and you'll need to be able to call those functions the c++ library exposes. You can look at them with readelf -s.

The functions your wrapper exposes, however, will need to be marked extern "C" so that their names are not mangled. Then you will be able to call them from your pure C application.

Static vs. Shared library shouldn't really matter here. It's just a matter of the correct symbols being generated so that linking can happen.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文