tags:

views:

148

answers:

3

How can we use any C library inside our C++ code? (Can we? Any tuts on that?) (I use VS10 and now talking about libs such as x264 and OpenCV)

+10  A: 

Yes, the only thing you need to do is to wrap the #include statement with extern "C" to tell the C++ compiler to use the C-semantics for function names and such:

extern "C" {
#include <library.h>
}

During linking, just add the library like any normal C++ lib.

Aaron Digulla
That's fine as long as the C header doesn't use any C++ keywords (like `new` or `private`) as names.
Mike Seymour
and how about calling functions - if I had 'write_frame' in library.h in C++ i could just call it like normal function?
Blender
@Ole: yes, as long as it's declared `extern "C"` you can call it like any other function.
Mike Seymour
Yes, it should work fine.
Crashworks
A: 

As far as I know, if you have the library you want to use, you just stick an include in your header file and you can use it. from there on.

OddCore
You need `extern "C"` to tell the C++ compiler that the library functions have C-style linkage, and some C headers might contain names that are invalid in C++.
Mike Seymour
+2  A: 

Well you can use any C library from your C++ code. That's one the cool thing with C++ :-) You just have to include the libraries headers in your C++ code and link with the libraries you use.

Any good library handles its header inclusion from C++. If it is not the case you have to do it yourself with things like :

#ifdef __cplusplus
extern "C" {
#endif

#include "c_header.h"

#ifdef __cplusplus
}
#endif

Edit: As Mike said, the ifdef parts are only needed if you do not know if your file will be used with C or C++. You can keep them if the file is a header of an API header for example.

By the way, opencv handles the inclusion by C or C++ (thus you already have the #ifdef part in opencv headers). I do not know for x264 ...

my2cents

neuro
You don't need `#ifdef __cplusplus` if you know you're writing C++. That's only needed in a header designed for inclusion by both languages.
Mike Seymour
@Mike: Of course you're right. I've probably written too many frameworks / libs :) Sorry for my bad habits ;)
neuro