I'm trying to create a static library to allow me to use a C++ API in my C program. To get started, I'm trying to call an API function called APIName::Api_init()
; So far, I have created a "wrapper" library which has the following:
c_api.h:
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC int apiname_api_init(char const * user_app_name);
EXTERNC void apiname_api_shutdown();
#undef EXTERNC
c_api.cpp:
#include "c_api.h"
#include "../include/apiname/api.h" // Link to header files from API provider
int apiname_api_init(char const * user_app_name) {
return to_return_code(APIName::Api_init(user_app_name));
}
void apiname_api_shutdown() {
return APIName::api_shutdown();
}
I then compile this into an object file called apiwrapper.o using the following command:
g++ -L../include/libs -lapinameapi -shared -fPIC -c -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX c_api.cpp -o lapiwrapper.o -lrt
where apinameapi
is the shared library from the API provider. This works fine. I then generate the library file using:
ar rc libapiwrapper.a apiwrapper.o
Again, this is fine.
Now I create my C file (mycode.c), which contains:
#include "mycode.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int connectToApi() {
// Init API
rc = apiname_api_init("programname");
}
The header file mycode.h contains:
#include <stdbool.h>
#include <stdint.h>
#include "c_api.h"
(obviously there's other stuff as well, but I've left it out for brevity).
So, I compile my main program using:
gcc -Linclude/libs -lapiwrapper -shared -DKXVER=3 -fPIC -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -Iinclude -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX src/mycode.c -o lib/mycode.so -lrt -Wno-discarded-qualifiers -Wno-incompatible-pointer-types
which is also fine. Then, I run the program (this particular file gets loaded by another piece of code), and I get
undefined symbol: apiname_api_init
It seems that it's not finding the function in the library file. Where am I going wrong? This is my first time building a library, so it's probably something fairly basic.
EDIT: I think the issue may be coming from the fact that the final compilation (which creates mycode.so) is producing a shared object file, and I need that to run on its own (without needing my generated library file to be present as well). I have to run the final object from another program, so it needs to be standalone. Is there a way I can link it to "bundle" everything together into one final so file?