Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we use any C library inside our C++ code?

Tags:

c++

c

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)

like image 347
Rella Avatar asked Jul 13 '10 09:07

Rella


2 Answers

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.

like image 61
Aaron Digulla Avatar answered Oct 12 '22 05:10

Aaron Digulla


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

like image 45
neuro Avatar answered Oct 12 '22 05:10

neuro