Reputation: 53
Usually to get a C library working from C++ you have to include it with extern "C" { #include <clibrary.h> }
. Many libraries will include in their header files code like #ifdef __cplusplus extern "C" { ...
to make them more user friendly to C++ code (e.g. pthread.h
). Sometimes this is not the case. For instance, stdio.h
has no such #ifdef
, yet I can still compile & link the usual #include <stdio.h> int main() {printf("Hello");}
using a C++ compiler without wrapping it in an extern "C"
statement. Why is this?
Upvotes: 3
Views: 681
Reputation: 385144
Usually to get a C library working from C++ you have to include it with
extern "C" { #include <clibrary.h> }
.
Only when the library was not designed with C++ compatibility in mind. But this is a hack.
Many libraries will include in their header files code like
#ifdef __cplusplus extern "C" { ...
to make them more user friendly to C++ code (e.g.pthread.h
)
Yes, a good library will do this.
As a result, you do not need to and should not add another extern "C"
around the #include
.
stdio.h
is an example of a header that will be doing this properly (see below).
For instance,
stdio.h
has no such#ifdef
Sure it does! Follow the money trail…
why isn't extern always needed?
So, in conclusion, you only need to do this yourself when the author of the header file didn't do it for you. When the author of the header file did it, you do not need to do it.
Upvotes: 4
Reputation: 238321
For instance, stdio.h has no such #ifdef
It probably does. Regardless, <stdio.h>
is a header provided by the C++ standard library (inherited from the C standard library). It is guaranteed to work without extern "C"
as are all standard headers.
Note that the usage of <name.h>
name of the inherited standard headers in C++ instead of <cname>
is deprecated in the current edition of the standard and has been identified as a candidate for removal in future revisions.
why isn't extern always needed?
Simply because some headers have been written to support C++ directly, and so do it by themselves.
Upvotes: 1