Creating a C Library: Difference between revisions

[unchecked revision][unchecked revision]
Content deleted Content added
→‎Implementing: added section
update the notes for NO_IMPLICIT_EXTERN_C for GCC 9 and above.
Line 144:
Traditionally C++ programs can use the C headers, even though such headers are written in C and have C linkage. Unless you specify otherwise, GCC will assume that header files found in your system include directory are written in C and have C linkage. This is done by GCC automatically inserting extern "C" { ... } around all included system headers. However, this may lead to strange linking-failures if you try to use C++ headers from the system include directory. The key solution is to make your C headers explicitly compatible with C++ and tell GCC that you understand C++.
 
Telling'''For GCC versions < 9''', telling GCC that your headers understand C++ is done by having the following in your OS-specific gcc/gcc/config/myos.h:
 
<source lang="c">
Line 151:
#define NO_IMPLICIT_EXTERN_C 1
</source>
 
'''For GCC versions >= 9''', [https://patchwork.ozlabs.org/patch/934478/ this patch] changed the behaviour; they have made <tt>NO_IMPLICIT_EXTERN_C</tt> a so-called "poisoned identifier", so compiling your OS-specific toolchain will fail. If you read the linked patch above, you will realise that they decided to invert the behaviour, such that system headers are assumed to understand C++ by default. So, in theory, you do not need those two lines above at all, and it should Just Work (tm).
 
If, instead, your system headers indeed ''do not'' support C++ (why?), you can <tt>#define SYSTEM_IMPLICIT_EXTERN_C 1</tt>, as they have done for AIX.
 
Adding support for C++ in your C header files (such as stdio.h) is very simple. Previously GCC automatically added extern "C" around all headers if compiling C++, but now we'll need to do it ourselves. The key feature is that we don't need to do this on C++-only headers, meaning that C++ headers will now actually work, instead of GCC assuming they have C-linkage. For instance, you can change your stdio.h to be of this form: