Sunday, October 24, 2021

[SOLVED] Compile C shared object with C++ files

Issue

I have a C shared object (.so file) and i can only compile it using gcc because it uses C only functions like strcpy_s.

And i have a C++ code that contain some C++ only libraries.

Is that possible to compile the shared object with gcc and my code with g++ together ?


Solution

Sure, you can link your C++ program with your shared C library. Just make sure that you tell the C++ compiler that the functions in that library have C linkage by adding extern "C" { ... } around the functions in your C library's header file:

shared_c_lib.h

#ifdef __cplusplus
extern "C" {
#endif

// all your C functions declarations/prototypes

#ifdef __cplusplus
} // extern "C"
#endif


Answered By - Ted Lyngmo