Making a C library header compatible with C

suggest change

A C library header can usually be included into a C++ program, since most declarations are valid in both C and C++. For example, consider the following foo.h:

typedef struct Foo {
    int bar;
} Foo;
Foo make_foo(int);

The definition of make_foo is separately compiled and distributed with the header in object form.

A C++ program can #include <foo.h>, but the compiler will not know that the make_foo function is defined as a C symbol, and will probably try to look for it with a mangled name, and fail to locate it. Even if it can find the definition of make_foo in the library, not all platforms use the same calling conventions for C and C++, and the C++ compiler will use the C++ calling convention when calling make_foo, which is likely to cause a segmentation fault if make_foo is expecting to be called with the C calling convention.

The way to remedy this problem is to wrap almost all the declarations in the header in an extern "C" block.

#ifdef __cplusplus
extern "C" {
#endif

typedef struct Foo {
    int bar;
} Foo;
Foo make_foo(int);

#ifdef __cplusplus
}  /* end of "extern C" block */
#endif

Now when foo.h is included from a C program, it will just appear as ordinary declarations, but when foo.h is included from a C++ program, make_foo will be inside an extern "C" block and the compiler will know to look for an unmangled name and use the C calling convention.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Linkage specifications:
* Making a C library header compatible with C

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
127 Linkage specifications
134 Semaphore
136 Debugging
139 Mutexes
142 decltype