Search code examples
c++linuxreferenceexportdynamic-library

Link dynamic shared library in Linux - Undefined reference to function


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!


Solution

  • 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)