0

I understand that when you include a c header in your c++ project you must wrap it with extern "C" because c++ and c have two different ways of identifying function. c will use the name to identify a function and c++ must use the name and the parameters to satisfy function overloading.

What I don't understand is why are there are c headers that don't require to be wrapped in extern "C" like windows.h??

3
  • 1
    windows.h is not a library. It is a header file, and a header is not a library. Commented Feb 8, 2013 at 17:59
  • @WilliamPursell By a library I did mean header file. But with your logic, you can't include a library in C++ compilation file anyways. Commented Feb 8, 2013 at 18:03
  • 1
    You are correct, it is not possible to include a library. You can include a header file, and you can link against a library. The two ought not be confused. Commented Feb 8, 2013 at 18:21

1 Answer 1

9

In general, wrapping a C header in extern "C" is not a good idea. The header might include other files that break when you do this. A C header that is designed to be used in C++ will handle extern "C" appropriately, without you having to do anything. Typical code:

#ifndef MY_HEADER_INCLUDE_GUARD
#define MY_HEADER_INCLUDE_GUARD

#ifdef __cplusplus
extern "C" {
#endif

/* C callable stuff goes here */

#ifdef __cplusplus
}
#endif

#endif /* MY_HEADER_INCLUDE_GUARD */
Sign up to request clarification or add additional context in comments.

4 Comments

The header might also define a struct with a member named class or a macro named string. (I've actually encountered both.)
But when you include headers like lua then you wrap it with extern "C", why did they not plan for that?
@Caesar: if a particular C header tells you that you can include it in C++, but must provide the extern "C" { ... } yourself, then of course you should do as you're told. But the reason there are headers for which you don't have to do this is precisely what Pete says in this answer: because those headers have been designed for use in both C and C++.
I always thought it was because the makers of lua believe in segregation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.