1

Posting a basic question about using C style .c and .h class in a C++ application. I have a library which is meant for C but based on the documentation i can also use for C++.

Should i need to rename the two files as .cpp and .hpp before i start including them in my project ? I tried to refer existing thread but it talks about other way crom cpp to c.

How to convert C++ Code to C

Community
  • 1
  • 1
linux developer
  • 821
  • 1
  • 13
  • 34

1 Answers1

5

No you don't. The .h extension is shared.

The implementation file extension depends on the compiler/IDE. For example, MSVS will compile .c files as C source code, and .cpp files as C++. That means you'll have to use

extern "C"

in the header if you use the C functionality in the C++ part of the project.

AFAIK you can compile .c files with g++ as C++, so the extension change is not necessary. Or you can compile them with gcc and use extern "C" again.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • As a minor note, it can be argued that it's "weird" to put `extern "C"` in a header file for a C library, since that syntax is C++. It's also possible to put `extern "C"` around the `#include` of the C header. – unwind Nov 13 '12 at 15:42
  • @unwind or surround it with `#ifdef __cplusplus`, but yes, that makes sense. – Luchian Grigore Nov 13 '12 at 15:47
  • I never thought about wrapping the actual #include with an extern "C" { } block. That's pretty smart. Oh preprocessor, how can you be abused? Let me count the ways. – Nik Bougalis Nov 13 '12 at 15:59
  • @NikB. - abused, indeed. Wrapping a standard header in an extern "C" block produces undefined behavior. Wrapping someone else's header in an extern "C" block may or may not work, depending on what's in the header. Imagine, for example, a header that #include's a C++ header... – Pete Becker Nov 13 '12 at 16:12