r/cpp_questions • • 2d ago

OPEN What is the difference between ABI and API and what does it mean to say that C++ does not have a stable ABI while apparently C has a simple and stable ABI?

Can some simple examples be given to clarify this seemingly complicated topic?

What exactly is at stake in making an ABI stable and simple? Who benefits?

60 Upvotes

43 comments sorted by

63

u/dodexahedron 2d ago edited 1d ago

API is about code (symbol naming mostly). Stable API means you can write code now and it should still compile on future versions. It makes no guarantees about already-compiled assets continuing to work together if compiled against different versions.

ABI is about the binary layout of things in the executable image, what shape the structures are, offsets of entrypoints for functions, calling convention, etc.

A stable ABI means that, for example, assets compiled originally against the same version should continue to work with each other even if one of them is later compiled against a different version.
It's important for dynamically linked software in particular, or else an application compiled against a shared dynamic library would break if either it or that library were updated without being re-compiled in that exact pairing (which would defeat a pretty major reason for dynamic linking).
Another teeny tiny case of ABI stability being critical is operating systems presenting a stable ABI to userspace applications. Some people have this bizarre desire for their applications not not break after a routine OS security patch.

Also, be aware that neither ABI nor API stability necessarily implies the other. You can have one, both, or neither.
However, certain kinds of API changes naturally do mean the ABI has definitely changed, too (e.g. changing the order of the parameters in a function is both an API and ABI change).

In short, API is a symbolic contract relevant at compile time (hence the P), and ABI is a binary contract relevant at link time (and, consequently, execution time) in the binary images (hence the B).

8

u/Impressive_Gur_471 2d ago edited 2d ago

As a coder who uses C or C++, should he only worry about API? He does not have to worry about ABI, right? Who decides the ABI? Is it the C++ standards committee? Or is it the chip makers such as Intel, AMD, etc.?

Does C++ compiler today being backward compatible mean that it is providing stable API or ABI?

(Sorry if these questions seem nonsensical or annoying...I just do not know what these terms mean and how they interact with each other at a higher level hence the ignorance and pointedness of questions)

22

u/Flimsy_Complaint490 2d ago

imagine a function that takes a struct. You add an optional char pointer to that struct.

The project still compiles. A char pointer will just be null or garbage and its optional to set. This is API stability. You handled both cases. No caller needs to do anything for this to work.

Now you compile your library and distribute it as an artifact, say a dll. They didnt update their code or recompile everything, just the library was swapped. The function signature is the same. They call your new function and get a crash - they allocated a struct thats N bytes and passed it, but its actually N+8 bytes and your library expected a a field the caller didnt allocate memory for and will therefore read 8 random bytes instead and magical things can happen, such as a crash or garbage computation. ABI stability was broken. the calling code expected one layout of the struct but its different.

How much you need to care about either is a depends. Breaking api stability for no reason is not nice to your consumers. ABI you can ignore if you can compile all your code and all your dependencies, else you need to care about it somewhat.

5

u/JVApen 2d ago

Lots of people are responsible for ABI. You have calling conventions, you have name mangling, you have standard library types, you have any other types and functions.

If you can write code without having to worry about ABI or API you are lucky. This can happen when your work produces an executable or when working in a monorepo and replace both exe and libraries. The opposite is being a library writer?

4

u/DontForgetWilson 2d ago edited 2d ago

ABI matters more or less to a coder depending on their usecase. For example, if you want to use a different language for a high performance section of code suddenly you need to care about how those two languages can interact (which is very influenced by ABI). Alternatively, you may want to guarantee that an executable is more compatible between different versions or variants of an OS. Relying on a less stable ABI makes that more challenging.

You aren't generally in charge of selecting the ABI as a coder, but it is part of language selection and there may be special compilation settings or macro usage related to it. For example, rust allows you to annotate functions to use the C ABI so that other languages can easily rely on that rust code more dependably.

3

u/vishal340 2d ago

a quick example is of ABI will be how int is stored. you can store from left to right or right to left. also there is ABI differences between c and c++ how union is stored but i don’t remember the details of it anymore

3

u/KlyptoK 2d ago edited 2d ago

If your write libraries for other developers to use and want other people to not suffer immensely, you really should care an insane amount about the ABI.

If you just use libraries, just be aware if they do or do not offer ABI guarantees and what that might mean for your development.

If you serialize data or write saves to disk, or talk directly with a network protocol, you care a lot about ABI stability in that subarea or maybe directly and clearly warn your users that you do not.

0

u/smdowney 2d ago

The standard ABI for everyone except Microsoft Windows:

Itanium C++ ABI - Reading Mode https://itanium-cxx-abi.github.io/cxx-abi/abi.html

The layout of data in a library is also called ABI, which is what people usually complain about, because if you change layout you risk incompatibility across boundaries.

The Python manylinux standards cover a lot of this so that you can get the right binary wheel for your platform.

3

u/Chippors 2d ago

Python? Where simply updating a library or accidentally having two versions installed will have a program that has worked for years suddenly crash on startup with an 'import' exception?! Meh. Color me unimpressed.

1

u/QuraToop314 2d ago

Do you hear from Python limited ABI, the stable API from Python?

0

u/JVApen 2d ago

"he"? It's an answer pointed towards you

12

u/nicuramar 2d ago

API isn’t code, it’s a contract. It doesn’t have to be code at all. ABI is much more low level.

3

u/dodexahedron 1d ago

The word "about" was lazily missing (though intended), so the intended point was exactly that.

So, I edited to add that plus a couple other details as well, to refine and clarify.

2

u/Relative_Bird484 1d ago

And ABI is also a contract.

API is a contract between programmers.

ABI is a contract between compilers/linkers.

3

u/efalk 1d ago edited 1d ago

Best answer, but I want to supplement a little.

API = Application Programming Interface. That's basically the library declarations and associated rules. As long as it's stable, a program and its libraries will continue to work together as long as they're compiled together. This is defined by standards committees for standard libraries. Defined by the library designers for other libraries.

ABI = Application Binary Interface. This is the set rules about where and how data is packed for function calls, data structures, and so forth. Defined by the people who define the processor architecture and/or the people who design the compiler. Presumably published so that anybody else developing compilers for that architecture will generate code that's compatible.

If the ABI (and the API) is stable, then code compiled with one version of the compiler will work with code compiled with another version.

I once worked for a large company that had dozens of major departments, each of which used a different version of Visual Studio. The .dll files were compatible but not the .lib files. You had to compile everything yourself to build an executable. There was a project to get the whole company switched over to the same version, but it wasn't easy because — guess what — the APIs weren't stable either. I don't think Microsoft's C++ was fully standards-compliant until v15. (This was over a decade ago, so memory's a little fuzzy here.)


Going back to your original question: the C ABIs are stable because it's an old, established language that has had no significant changes in a long time. C++ originally had an Achiles heel: function names are "mangled" so that a function declared void foo(int a, int b) would be named something like _foo_void_int_int so as not to be confused with void foo(float a, float b). The original C++ compilers didn't have a standard way to do this, so code generated by different compilers, or different versions of compilers, would not be compatible. I believe this has been cleared up by now.

(Again, working from memory here.)

17

u/mredding 2d ago

An API defines a software interface. It is a contract of what behaviors exist and how to call them. In C and C++, this is the definition of a header file. Headers define APIs.

Now the difference between a library and a framework has to do with who is in control of the implementation.

A library is an implementation, often as a .dll or .so, a .a or .lib. It is a library if YOUR PROGRAM maintains control. zlib is a library, just a bundle of tools. The standard template library is a library, and it's not all in headers, there's a runtime that is linked in to go with it.

A framework inverts control. The FRAMEWORK is in control, and you pass your implementation TO IT, and it's the framework that decides the lifecycle of the application. A framework can be implemented as a library, as a program, or as a service. As a library, you may have to do a little to get the framework up and running, but it possesses most of the agency of that program, or at least it's facet of it. Qt, Unreal, JUICE are all frameworks.

Notice libraries and frameworks both have APIs.

Win32 is not a library, and it's not a framework, because you control the lifecycle, and while frameworks provide structure, Win32 does not. This is a new category - an SDK, typically a PLATFORM SDK, a Software Development Kit. This is the foundation upon which you build programs for a platform. Open GL is its own platform, and there is the Vulkan SDK. SDKs also come with libraries, sometimes frameworks, tools, and documentation.

THEN THERE IS THE ABI...

This is the Application Binary Interface. This is how two binary units communicate with one another. Your program has to talk to the kernel and other system libraries. This defines how functions are named, and the binary formats so you can load a system library and FIND the entry point to the function. Your program has to speak enough of this language to load a library and call it's implementation. At the very least, your language and tools need to support a Foreign Function Interface.

If you want your program TO BE a system library, you need to present yourself as one. That means your functions have to follow the same conventions, your calling conventions have to be the same, down to value types and pointers or reference types, other contractual expectations.

A system ABI tends to be essentially whatever the native C compiler does, because most operating systems are written in C.

C++ makes things a bit more difficult. You have things like objects, with automatic functions like constructors. Only another C++ program is going to know to honor those conventions, a C or Fortran program won't. So it's very difficult to write a binary layer where a Fortran program is constructing C++ objects and calling such functions. This is why non-system ABIs are useless for everyone but other uses of THAT ABI - same language, same tooling.

C and C++ have different ABIs, essentially because C has a single flat namespace:

struct A {
  struct Inner { int x; } in; // Declares 'struct Inner' in the file scope
};

struct B {
  struct Inner { double y; } in; // COMPILE ERROR: redefinition of 'struct Inner'
};

There's only the global namespace to name Inner in the ABI, and C and the ABI correspond 1:1.

But C++ has hierarchical namespaces. The above code works just fine. But how do you do that? The system ABI is still a single flat namespace, but C++ isn't. Something has to give.

Enter: name mangling. The C++ language standard says nothing of it. This is a tooling solution to abstract the C++ nested namespace upon a flat namespace. So:

void foo(A::Inner);

Will become name mangled to something like _Z3fooN1A5InnerE following a naming schema that guarantees no ambiguity and will flatten into a single global namespace.

So a C program can load your C++ library and dlbind a function pointer to THAT function for that type. According to C and the ABI, it's not an A::Inner, it's an A5InnerE or a B5InnerE to distinguish between the two.

Since the language says nothing about mangling or how to do it, it's up to the tooling, and compilers and linkers do it differently. It can even change between versions of the same compiler. It's not portable and not consistent. When you're writing low level code like this, it's a major concern.

That's why C++ has extern "C", where we can tell the compiler we want the C/system ABI for this block of code, don't mangle it. But that means you're restricted to C rules and types.

This explanation is a bit of a rush job, but I hope it provides some clarity.

4

u/bacmod 2d ago edited 2d ago

Talking to you people is like talking to a technical specification of a combustion engine.

Leave some mystery out there.


Don't ban me I'm drunk

EDIT:

This explanation is a bit of a rush job, but I hope it provides some clarity.

I shudder thinking what would a non-rush post looked like.

2

u/mredding 2d ago

I left plenty of mystery. The reason I HAD to get as nuanced as I did is because there's so much blur in just the terminology - we all use "API" but struggle to define how it's distinct from an interface, framework, or SDK, I have no confidence if I just prompted ANYONE in the field on the spot they couldn't do it with specificity.

I felt if I left out any more detail, then there would be a gap OP didn't know was there, so wouldn't know to look it up.

3

u/bacmod 2d ago edited 2d ago

Libs: I use it to create API
API: I use it to create SDK
SDK: I use to to create FW
FW: I use to to create software

edit: You can't say you left anything to mystery when you start talking about

C based mangled _Z3fooN1A5InnerE schema

6

u/mgruner 2d ago

Imagine you have an application that uses an external library to operate. This external library can have a stable API, a stable ABI, both, or neither.

We can understand the whole stability concept by analyzing what happens to your program when you update this library to a new version.

The library has a stable API if you update it to the new version and all of the functions, constants, enums, declarations… you were using continue to work in your program. If any of that changes in a backward-incompatible way, it will break your code and you’ll need to manually change your program in order to make it work against the new API.

The library has a stable ABI if the binary-level conventions your program relies on remain the same. This includes memory layout, calling conventions, symbol naming, alignment, etc. For example, adding a new member to a struct can break the ABI because now that struct may have a different size. Imagine a function that received that struct by value: the compiler needs to know the size of the struct at compile time to correctly pass it as an argument. If the struct changed sizes, horrible things could happen at runtime.

Having a stable ABI means you could update the library without even recompiling your program. If the ABI is broken, but the API is stable, you’ll need to recompile the program. If the API compatibility is also broken, you’ll also need to fix the program to match the new API.

Now, the thing with ABI is that it’s not that trivial to understand. Many things are compiler-specific (one compiler may lay out one thing in memory differently than another). And, the more complex the language, the more potential ABI variations you’ll get across compilers and even compiler versions.

Neither the C nor the C++ language standard specifies an ABI, although both have stable ABIs for specific platforms and toolchains. However, C’s simpler language features make its ABI easier to define and maintain, making it less prone to the madness of ABI instability.

4

u/DeathLeopard 2d ago

When people complain about ABI stability in C++ relative to C I think they're really talking about two specific problems.

  1. Due to how templates work in C++ the implementation of library functionality ends up in headers which effectively makes it part of the interface. This is how an early, bad implementation (std::regex, gcc's copy-on-write std::string) gets locked in forever since it can't be fixed without forcing all callers to recompile.
  2. The C ABI is not defined by the C standard but each platform does generally define one because the OS functionality is usually exposed using C interfaces. All compilers for a platform will use that same ABI for C (and even non-C languages will use that for extern "C" FFI calls). C++ on the other hand has its ABI defined at the compiler level so two C++ compilers on the same platform don't necessarily produce code that can be linked together. Or even two different versions of the same compiler. Or the same compiler using different flags.

10

u/xiao_sa 2d ago

C++ DOES have a stable ABI

5

u/Dependent_Bit7825 2d ago

Links please. 

As far as I understand, The language does not specify an ABI. There are basically two de facto ABIs, not part of the standard, one, which most most unix-y things use and one for Microsoft-y stuff. Neither is a standard and they are as stable as the people who maintain them want them to be, no more no less.

6

u/xiao_sa 2d ago

The point is all of these are also true for C ABI. ISO C Standard does not specify it, instead it is vendor/platform specific. So for someone admits C has a stable ABI, C++ has one in the same sense.

1

u/ih-shah-may-ehl 2d ago

Person A says something is true, even if it isn't. And that give person B the justification to say something that's equally false because if person A can lie, so can person B?

3

u/kirgel 2d ago

It's in a weird spot. People who want to rely on C++ ABI across compilers can't do it. People who want to break C++ ABI also can't do it.

2

u/xiao_sa 2d ago

Actually mixing usage of clang and gcc is quite reliable, and that is the biggest selling point of clang after all. When people complains about C++ ABI, they are actually complains about ABI of some specific library, and most of time it is the standard library.
There are definitely some points to desire a ABI break in language ABI itself. One of them is to have a better C++ exception implementation.

3

u/ih-shah-may-ehl 2d ago

It literally does not. If it did, you could compile a piece of code with 1 compiler and reuse the binary in any other compiler. I'll let you in in a secret: The very reason DCOM exists is that there is no C++ ABI. the first 70 pages of the book I wrote about this very topic explain this in detail. Calling conventions, memory layout, and a bunch of other stuff is heavily compiler and platform dependent.

3

u/Discordbothost 2d ago

When testing a shared-library update, keep the old executable and run it against the new library before rebuilding it. Successful linking alone doesn't prove ABI compatibility: a symbol's name can stay the same while the expected arguments change.

2

u/plugwash 1d ago

What is the difference between ABI and API

An API is for source code, and ABI is for binaries.

ABI means different but related things when we talk about compilers or we talk about libraries.

When we talk about compilers ABI refers to the set of rules we use to translate source code constructs into binary constructs. How does the stack work? how are parameters passed? what size are data types? how are structures laid out? and so-on.

When we talk about libraries, ABI reffers to the interface presented by the compiled library. This depends on both the ABI of the compiler and the content of the library's header files.

Importantly changes in a library can break the ABI without breaking the ABI, consider for example a structure whose only use is to be returned from a function. If I add a field to the structure so the function returns more information then I have broken the ABI of the library but not it's API.

what does it mean to say that C++ does not have a stable ABI while apparently C has a simple and stable ABI?

Neither the C or the C++ standards defines an ABI. As far as the language is concerned each implementation can choose it's own ABI.

In practice though, the C ABI for a given platform tends to be relatively simple, stable and agreed upon by different compilers targeting that platform.

C++ is a much more complex language than C and so the ABI of the compiler is inevitably also much more complex. The nature of C++ also means that far more internal details of a library tend to become part of the library's ABI.

g++ has tried very hard to maintain a stable ABI over many years. Clang++ has adopted the same ABI at the compiler level but the library ABI for the standard C++ libraries provided by C++ and Clang differ. Even then there have been a few ABI changes over the years, with hacks to allow some level of library interoperability.

For years Microsoft used to declare a C++ ABI break with each new version of visual C++, but I belive they have stopped this in recent years.

2

u/conundorum 23h ago

An API is the interface between two codebases, such as between a program and a library or a driver; the "supplier" codebase will present the API as a means for the "consumer" to link up with it. (E.g., OpenGL or DirectX.) An ABI is the interface between object files, that allows two programs to connect with each other after being compiled. (E.g., name mangling schemes, ELF & P/Invoke, actual struct layouts, etc.)

For a good image, think of electrical wiring. The outlet is the API, and the power grid is the ABI. Most houses will present at least two APIs (the standard outlet for most things, and the heavy-duty outlet for large appliances like ovens), both of which sit on top of the ABI. You can change the API without changing the ABI (you can provide both grounded and ungrounded outlets, tied to the same grid), though you might have problems if the API implies an ABI it doesn't actually support (using a European outlet for a house on the North American grid is a recipe for disaster). If the consumer needs a different API, they might provide a wrapper to interface with your API (computer components & accessories that need a transformer typically plug into a standard grounded outlet, then have an outlet for a standard UPC computer power cord; your tower's PSU typically uses a cord that has a standard wall plug on one end, and a UPC plug on the other end). Different ABIs are usually paired with different APIs, but this isn't a hard requirement (NA and Euro wall sockets have different designs so you can't mix them up, but everyone uses the same UPC plug & socket; wall sockets use unique APIs for each grid, but UPC devices use the same API and a selector switch to identify the ABI in use).

2

u/CreepyWritingPrompt 20h ago

API is functions and data structures. ABI defines how those things are implemented in the hardware.

Sometimes when someone says ABI they include the API in that - so the entire interface of some software thing, all the way down to the hardware. Eg, when people talk about software being compatible with the linux ABI, they are talking about what syscalls exist, what they do, AND how they are invoked (what registers do what)

Other times, ABI specifically means "how are functions called", "how is data arranged". Such as in the context of a programming language discussion. Like this one

3

u/JVApen 2d ago
  • API: when changed, you have to update your code to update your code to use the new version
  • ABI: you have to replace binaries to use the new code

You can break the API without breaking the ABI, for example:

using SomeName= int;
void func(SomeName val);

becoming

using Value = int;
void func(Value val);

You can also break the ABI without breaking the API:

struct S
{
    S() {}
};

becoming

struct S
{
    S() = default;
};

What do they mean when the talk about unstable ABI? Almost any change to your code will break ABI. Even the people working for years on the standard have to backtrack if it turns out they accidentally broke ABI (ignoring the question on wether that's a good thing or not). Also people working on compilers break it without realizing. Clang has flags to select the version who's ABI to use.

What do people consider a stable ABI? C. Instead of mangling every function into a name, the only use the function name and ignore everything else. In that, changing a 2 to 3 argument function does not break the ABI as you can swap the binaries and the exe starts. You will have troubles when that function is used.

3

u/nybble41 1d ago

In that, changing a 2 to 3 argument function does not break the ABI as you can swap the binaries and the exe starts. You will have troubles when that function is used.

The expected function arguments are part of the ABI, so this is still an ABI break even if dynamic linking succeeds and the executable starts.

If the extra argument is optional (e.g. passing NULL gives the 2-argument behavior) and symbol versioning was enabled for previous version(s) of the library then the ABI break can be avoided without changing the function name by adding a versioned wrapper function. The wrapper will only be used by executables originally linked against the older version of the function; any newly linked executable would get the latest version. The GNU C standard library (glibc) makes extensive use of this feature to maintain ABI compatibility with executables and other libraries linked against older glibc releases.

3

u/GoogleIsYourFrenemy 2d ago

The C ABI is not simple.

4

u/tracernz 2d ago

And also not standardised.

3

u/alfps 2d ago edited 2d ago

❞ What is the difference between ABI and API

ABI = Application Binary Interface, the memory layout of things. This includes not only memory layout of types but also of function call frames, exception handling, ...

API = a misnomer really, but in C++ it is the set of declarations that a logical module or library exposes, in particular the set of functions.

In web development an API is correspondingly the set of logical functions that a server process exposes to the net.


❞ and what does it mean to say that C++ does not have a stable ABI while apparently C has a simple and stable ABI?

A literal reading of that question is that an ABI is stable if it does not change in a way that makes existing code that depends on it, stop working.

But that view does not make sense for the C versus C++ distinction.


The common problem with a C++ ABI versus C ABI is that even though basic types typically are the same for all compilers on a given platform (with some exceptions e.g. long double), in C++ the ABI also includes

  • layout of standard library classes like std::string,
  • special call conventions for method calls,
  • exceptions,

and possibly more that my association circuit failed to pop up (i'm still on first cup of coffee this morning), where all of this depends on the compiler and the standard library implementation.

So a shared library exposing a function returning std::string can in practice only be used with a given compiler (such as Visual C++ or g++) and compilers that are ABI-compatible with it (e.g. clang-cl or the Intel optimizing compiler for Visual C++, and clang++ for g++).

I think this is what you intended to ask about, and then it came out wrong when you put that question into words.

1

u/No_Mango5042 2d ago

The ABI is outside the scope of the standard. It would allow you to compile code on one machine and link to it or run it anywhere. In reality it’s easy to produce incompatible binaries, due to language version, compiler flags, calling convention, macros, platform, compiler, standard library version, etc. It’s vendor-specific what actually works, and yes it’s painful.

1

u/flatfinger 2d ago

The reason C became popular, even before there was a standard, is that it wasn't so much a language as a recipe for producing language dialects tailored to individual platforms and purposes. The term "high-level assembler" (a usage the C Standards Committee was, until recently, expressly chartered not to preclude) should be viewed not just as a high-level language that can be used to do things that would typically require assembly language, but also as a language for producing high-level assemblies.

On many platforms' assemblers, the act of putting a piece of code after a label doesn't attach any particular semantics beyond the fact that the label will be assigned the address of the first instruction following it. The assembler would neither know nor care how the code may use any registers, nor whether it alters them, leaves them alone, or uses them temporarily within a save/restore construct. It's possible and sometimes useful to write assembly language programs where different chunks of code treat registers or parts of the stack frame differently, but it's often simpler to have most pieces of code follow a consistent practice where certain things are to be left undisturbed, certain things may be freely used and overwritten, and others may be used if their values are saved beforehand and restored afterward. Pieces of code which follow such conventions may then be used as high level assemblies.

An ABI is a specification for how high-level assemblies should interact with each other. Sometimes the designer of an execution environment will specify an ABI, and sometimes the first entity to produce a C compiler for a platform will invent one, which others may or may not follow.

An API is generally a specification for a particular set of routines, rather than a general recipe for how routines should work with each other. An ABI may specify that every code label should hold the address of the second byte of the first instruction of a routine (that sounds weird, but it's how the normal ARM ABI works), while an API may specify that InitWoozle is the label for a function that expects to be passed certain parameters and will process them a certain way.

1

u/Adexsi29631 2d ago

Programming interface versus binary interface

0

u/Chippors 2d ago

By the same token C doesn't have a stable ABI either. One library may have a function crc16(const void* buf, size_t len), another version a crc16(size_t len, const void* buf), and although both of them work perfectly fine when used appropriately, linking with them in the wrong order will have your program crash when calling crc16().