且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

适用于 Linux 和 Windows 的 C++ 跨平台动态库

更新时间:2023-02-12 14:07:18

总的来说,有两个问题需要你关注:

In general, there are two issues you need to be concerned with:

  1. 要求,在 Windows 上,您的 DLL 显式导出应该对外界可见的符号(通过 __declspec(dllexport)
  2. 能够维护构建系统(理想情况下,不必维护单独的 makefile 和 Microsoft Visual C++ 项目/解决方案)

首先,您需要了解 __declspec(dllexport).在仅限 Windows 的项目中,通常这是按照我在 的回答中描述的方式实现的这个问题.您可以通过确保已定义导出符号(例如 MY_PROJECT_API)但在为 Linux 构建时扩展为空来进一步扩展此步骤.这样,您可以根据 Windows 需要将导出符号添加到代码中,而不会影响 linux 构建.

For the first, you will need to learn about __declspec(dllexport). On Windows only projects, typically this is implemented in the way I describe in my answer to this question. You can extend this a step further by making sure that your export symbol (such as MY_PROJECT_API) is defined but expands to nothing when building for Linux. This way, you can add the export symbols to your code as needed for Windows without affecting the linux build.

第二,你可以研究某种跨平台的构建系统.

For the second, you can investigate some kind of cross-platform build system.

如果您对 GNU 工具集感到满意,您可能需要研究 libtool(也许与 automake 和 autoconf 结合使用).这些工具通过 CygwinMinGW/MSYS.MinGW 还为您提供了交叉编译选项,即在运行 Linux 的同时构建您的原生 Windows 二进制文件.我发现有助于导航 Autotools(包括 libtool)的两个资源是 "Autobook" (特别是关于 DLL 和 Libtool) 和 Alexandre Duret-Lutz 的 PowerPoint 幻灯片.

If you're comfortable with the GNU toolset, you may want to investigate libtool (perhaps in conjunction with automake and autoconf). The tools are natively supported on Linux and supported on Windows through either Cygwin or MinGW/MSYS. MinGW also gives you the option of cross-compiling, that is, building your native Windows binaries while running Linux. Two resources I've found helpful in navigating the Autotools (including libtool) are the "Autobook" (specifically the section on DLLs and Libtool) and Alexandre Duret-Lutz's PowerPoint slides.

正如其他人提到的,CMake 也是一种选择,但我自己不能说.

As others have mentioned, CMake is also an option, but I can't speak for it myself.