wouldnotliketo
wouldnotliketo

Reputation: 323

Undefined symbol error in a shared library loaded at runtime

(I know various iterations of this question are asked here routinely but I didn't find anything that helped)

I'm trying to write a simple dynamic library and load it at runtime.

The library files:

mul.h

int mul(int a, int b);

mul.cpp

#include "mul.h"

int mul(int a, int b) {
    return a * b;
}

Then I have this Makefile:

mul.cpp: mul.h

mul_lib: mul.cpp
    g++ -Wall -fPIC -shared $< -o bin/libmul.so

bin/test.o: mul_lib
    g++ test.cpp -ldl -o bin/test

So I have created an .so file, and I checked using nm that there's a symbol for mul... or rather what I assume is the symbol for mul:

>nm -D bin/libmul.so 
                 w __cxa_finalize
                 w __gmon_start__
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
00000000000010f9 T _Z3mulii

In test.cpp, I'm trying to load this library with dlopen:

    typedef int (*mul_func)(int a, int b);

    void* mul_lib = dlopen("bin/libmul.so", RTLD_NOW);
    if (!mul_lib) {
        /* fail to load the library */
        fprintf(stderr, "Error: %s\n", dlerror()); // we don't exit here, library loaded
        return 2;
    }
    mul_func* func = (mul_func*)dlsym(mul_lib, "mul");
    if (!func) {
        fprintf(stderr, "Error: %s\n", dlerror()); // we exit here
        return 2;
    }
    (*func)(2, 4);
    dlclose(mul_lib);

But I'm getting bin/libmul.so: undefined symbol: mul I don't understand why. The symbol is present in the object file, it seems, and it's loaded correctly (I assume), so why is the symbol absent?

Upvotes: 0

Views: 1482

Answers (1)

wouldnotliketo
wouldnotliketo

Reputation: 323

Turns out declaring a function like this works:

extern "C" int mul(int a, int b);

For more information on why, see this comment.

Upvotes: 2

Related Questions