Using C Libraries for C++ Programs
Yes, C++ can compile C with a C++ compiler and you can link C++ against C. Just be sure that any C function you call uses C linkage. This is made by enclosing the prototype of the C function by an extern "C"
#ifdef __cplusplus
extern "C"{
#endif
void c_function_prototype();
#ifdef __cplusplus
}
#endif
The headers for the library you are trying to use may already do that.
Sure ... C code is called from C++ all the time. For instance, most OS libraries are written in C rather than C++. So whenever you're making syscalls from your C++ code to perform tasks that are handed over to the OS kernel, those are going through C-code calls.
Just be sure to include the proper headers and link against the C-libraries in question at compile time. Also remember to use extern "C"
to specify C-linkage for the C-library functions if the header files have not already declared them as such. Keep in mind that some libraries may not have declared their functions specifically using extern "C"
, but may have used a pre-processor token to-do so. So you'll want to check for that as well before you assume the library writers did not already define their library as having C-linkage.
linking custom libraries using gcc
can be done with the -l
switch. If you need to specify a custom directory for where the libraries are located, that can be done with the -L
switch. So for instance:
g++ -std=c++11 my_code.cpp -lmy_library -L/custom_directory_path
Note that the -l
and -L
switches come after the code or object files you're compiling, and if you're library is something like libjpg
, or librobotics
, etc., drop the lib
part of the name when you append it to the -l
switch.