Question

I know there are many questions related to shared libraries on Linux but maybe because I'm tired of having a hard day trying to create a simple dynamic library on Linux (on Windows it would have taken less than 10 minutes) I can't find what happens in this case. So, I am trying to create a library to be linked at build-time and used at run-time (not a static library, not a library to be embedded into the executable, in other words). For now it contains a simple function. These are my files:

1.

// gugulibrary.cpp
// This is where my function is doing its job

#include "gugulibrary.h"

namespace GuGu {
    void SayHello() {
        puts("Hello!");
    }
}

2.

// gugulibrary.h
// This is where I declare my shared functions
#include <stdio.h>

namespace Gugu {
    void SayHello();
}

3.

// guguapp.cpp
// This is the executable using the library
#include "gugulibrary.h"

int main() {
    GuGu::SayHello();
    return 0;
}

This is how I try to build my project (and I think this is what is wrong):

gcc -Wall -s -O2 -fPIC -c gugulibrary.cpp -o gugulibrary.o
ld -shared -o bin/libGugu.so gugulibrary.o
gcc -Wall -s -O2 guguapp.cpp -o bin/GuGu -ldl
export LD_LIBRARY_PATH=bin

This is saved as a .sh file which I click and execute in a terminal. The error I get when trying to link the library is this:

/tmp/ccG05CQD.o: In function `main':
guguapp.cpp:(.text.startup+0x7): undefined reference to `SayHello'
collect2: ld returned 1 exit status

And this is where I am lost. I want the library to sit in the same folder as the executable for now and maybe I need some symbols/definitions file or something, which I don't know how to create. Thanks for your help!

Was it helpful?

Solution 2

You are inconsistent with your GuGu, there are also Gugu's running around, this needs to be made consistent, then it works (At least on my computer are some Gugu's now)

OTHER TIPS

In your C++ file, GuGu::SayHello is declared as a C++ symbol. In your header, you are wrapping it in an extern "C" block. This is actually undefined, as you aren't allowed to use C++ syntax (namespace) in that context. But my guess is that what the compiler is doing is ignoring the namespace and generating a C symbol name of "SayHello". Obviously such a function was never defined by your library. Take out the extern "C" bits, because your API as defined cannot be used from C anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top