简体   繁体   中英

Using C++ shared library from C

I have a C library that I'm using from my C application, with dlopen annd dlsym . Everything work fine, but I rewrote the C library to C++ and now my main application stopped working with the library.

It can't find the symbols (the function), even thow the code is exactly the same, just that I changed my compilation method.

This is how I got my lib before:

$(PLUGINS_DIR)/%.so: $(PLUGINS_DIR)/%.o
    $(CC) $^ -o $@ -shared

$(PLUGINS_DIR)/%.o: $(PLUGINS_DIR)/%.c
    $(CC) -c $< -o $@ -pedantic -g -Wall -std=gnu99 -fpic -I.

And this is how I get it now:

$(PLUGINS_DIR)/%.so: $(PLUGINS_DIR)/%.o
    $(CPP) $^ -o $@ -shared

$(PLUGINS_DIR)/%.o: $(PLUGINS_DIR)/%.cpp
    $(CPP) -c $< -o $@ -pedantic -g -Wall -fPIC -I.

How should I compile mmy C++ library so that I can use it from my C code?

That's because of name mangling, the function names get mangled in c++ to provide function overloading, if you need to use these functions in c, the declare the functions with extern "C" so the compiler wont mangle the names of the functions.

So adding this prototype for function void function() {}

extern "C" void function();

would do it. And I assume you can figure out how to fix other functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM