便携式图书馆的语言选择
我想编写一个库,该库将从 Windows、Linux 和 OS/X 等现代操作系统上运行的其他程序动态链接(即,它将部署为 .dll
或 .so
模块)。
在这种情况下最合适的语言是什么? 我应该坚持使用纯 C 吗? 或者C++也可以吗?
I want to write a library which will be dynamically linked from other programs running on modern operating systems like Windows, Linux and OS/X (i.e. it will be deployed as a .dll
or .so
module).
What is the most appropriate language in that case? Should I stick with plain C? Or is C++ also ok?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 C 或 C++ 来实现,但我建议使用纯 C 来定义接口。这样会更容易集成。
You can use either C or C++ for the implementation, but I would recommend to define the interface in pure C. It will be much easier to integrate.
创建以二进制形式分发的 C++ 库的困难在于,您的客户(库的用户)通常只能使用与您创建库相同的 C++ 编译器。 如果您想了解最新情况而他们不这样做,或者如果他们想了解最新情况而您不这样做,这可能会出现问题。 如果您处理源代码,那么这不是一个问题,只要您的 C++ 具有足够的可移植性,允许您的客户使用的所有编译器都可以使用它。
如果可以从 C 使用代码,我可能会编写 C 接口代码。 或者,提供两个接口 - 本机 C++ 接口和 C 接口。 但这不仅仅是一个 C 接口。 另一方面,C++ 接口(可能使用 STL 迭代器等)可能有好处,这可能会影响您的决定。
The difficulty with creating a C++ library distributed in binary form is that your customers - the users of the library - are typically constrained to use the same C++ compiler as you created the library with. This can be problematic if you want to keep up to date and they don't, or if they want to keep up to date and you don't. If you deal in source, this is less of an issue, as long as your C++ is portable enough to allow it to be used by all the compilers your customers use.
If the code may be used from C, I'd probably code to a C interface. Alternative, provide two interfaces - the native C++ interface and a C interface. But that's more work than just a C interface. On the other hand, there may be benefits from a C++ interface (perhaps using STL iterators, etc) and that could sway your decision.
我还想说 C 是最低公分母。 如果 C++ 包装器与调用应用程序集成得更好,您始终可以选择将 C++ 包装器写入核心库。
I would also say that C is the lowest common denominator. You always have the option of writing a C++ wrapper to the core library if this integrates better with the calling application.
我想说 C 是最可移植的,但 C++ 也是可行的。
I'd say C is the most predictably portable, but C++ is doable.
考虑最小公分母因素,让图书馆的消费者做出最适合他们的决定。 extern c 的构造可能仍然让一些人感到困惑,并且您希望您的库能够走得更远并覆盖最广泛的受众。 绝对要让接口纯c。 只要您避免一些阴暗的角落(如 STL),C++ 就很好。 C 是最便携的,没有之一。 为所有可用平台创建库并非易事,因此请务必查看此处 一些提示。 您可能还想考虑使用 autoconf 等。
Consider the factor of lowest common denominator and making consumers of your libraries make the decisions that are best for them. The construct of extern c probably still confuses some people and you want your library to travel far and reach the widest audience. Definitely make the interfaces pure c. C++ is fine provided you avoid some of the darker corners (like STL). C is the most portable bar none. Creating libraries for all available platforms is no small feat so be sure to take a look here for some hints. You might also want to consider using autoconf and the like.