GCC vs MS C++ compiler for maintaining API backwards binary compatibility

风格不统一 提交于 2019-11-28 18:48:37
Artyom

First of all these policies are general and not refer to gcc only. For example: private/public mark in functions is something specific to MSVC and not gcc.

So basically these rules are fully applicable to MSVC and general compiler as well.

But...

You should remember:

  1. GCC/C++ keeps its ABI stable since 3.4 release and it is about 7 years (since 2004) while MSVC breaks its ABI every major release: MSVC8 (2005), MSVC9 (2008), MSVC10 (2010) are not compatible with each other.
  2. Some frequently flags used with MSVC can break ABI as well (like Exceptions model)
  3. MSVC has incompatible run-times for Debug and Release modes.

So yes you can use these rules, but as in usual case of MSVC it has much more quirks.

See also "Some thoughts on binary compatibility" and Qt keeps they ABI stable with MSVC as well.

Note I have some experience with this as I follow these rules in CppCMS

Tobias Langner

On Windows, you basically have 2 options for long term binary compatibility:

  1. COM
  2. mimicking COM

Check out my post here. There you'll see a way to create DLLs and access DLLs in a binary compatible way across different compilers and compiler versions.

C++ DLL plugin interface

The best rule for MSVC binary compatibility is use a C interface. The only C++ feature you can get away with, in my experience, is single-inheritance interfaces. So represent everything as interfaces which use C datatypes.

Here's a list of things which are not binary compatible:

  • The STL. The binary format changes even just between debug/release, and depending on compiler flags, so you're best off not using STL cross-module.
  • Heaps. Do not new / malloc in one module and delete / free in another. There are different heaps which do not know about each other. Another reason the STL won't work cross-modules.
  • Exceptions. Don't let exceptions propagate from one module to another.
  • RTTI/dynamic_casting datatypes from other modules.
  • Don't trust any other C++ features.

In short, C++ has no consistent ABI, but C does, so avoid C++ features crossing modules. Because single inheritance is a simple v-table, you can usefully use it to expose C++ objects, providing they use C datatypes and don't make cross-heap allocations. This is the approach used by Microsoft themselves as well, e.g. for the Direct3D API. GCC may be useful in providing a stable ABI, but the standard does not require this, and MSVC takes advantage of this flexibility.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!