Using C Libraries for C++ Programs Using C Libraries for C++ Programs c c

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 __cplusplusextern "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.


Yes. To use C library function use extern "C" as below in your .cpp program, myprog.cpp

extern "C" {    // C Function call    cfunc();}int main(){    cfunc();    return 0;}

This cfunc should be defined in c library as belowprog.c

#include <stdio.h>void cfunc(){   printf("This is from c library");}

Then you need to create .o object file and .so shared object files for your C library as below

$] gcc -c prog.c -o prog$] gcc -shared -o libprog.so prog.o$] export LD_LIBRARY_PATH=/path/to/clibrary:$LD_LIBRARY_PATH$] g++ -L/path/to/clibrary myprog.cpp -o myprog.o -lprog