Find the answer to your Linux question:
Results 1 to 2 of 2
I am trying to learn more about creating and using shared libraries in linux. I learn best from hands on experience so what I am trying to do is take ...
  1. #1
    Just Joined!
    Join Date
    Jun 2008
    Posts
    1

    create shared libraries

    I am trying to learn more about creating and using shared libraries in linux. I learn best from hands on experience so what I am trying to do is take the file foo.cpp which contains one function:

    Code:
    #include <iostream>
    
    void print(char* message){
        cout << message << endl;
    }
    I made this file a shared library with this command:
    Code:
    g++ -shared -Wl,-soname,libZACH.so.1 -o libZACH.so.1 foo.o -lc
    I created a header file for foo.h which has the function prototype in it and then included it into my next file, bar.cpp, which tries calling the function print from the shared library. I compiled bar with this command:
    Code:
    g++ bar.cpp -LZach
    The output I get from this command is:
    Code:
    undefined reference to `print(char*)'
    I also tried moving my library to /usr/lib to see if that would make it work but it did not. I really want to learn how to create and use shared libraries, so if anyone can help me get this simple example to work I would greatly appreciate it.

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    Here's a working example...hope this helps

    getsetx.cpp

    int x = 0;

    int getx()
    {
    return x;
    }

    void setx(int val)
    {
    x = val;
    }


    test.cpp

    #include <iostream>
    #include <dlfcn.h>

    typedef int (*importgetx)();
    typedef void (*importsetx)(int);

    int main(int argc, char**argv)
    {
    int choice, val;
    importgetx GetX;
    importsetx SetX;

    void *handle = dlopen("/home/share/test/getsetx.so",RTLD_LAZY);

    GetX = (importgetx)dlsym(handle, "getx");
    SetX = (importsetx)dlsym(handle, "setx");

    while (true)
    {
    std::cout<<"(0)exit (1)view (2)set->";
    std::cin>>choice;
    std::cout<<"\n";

    if (choice == 0) break;

    if (choice == 1) std::cout<<GetX()<<"\n";

    if (choice == 2)
    {
    std::cout<<"enter a value->";
    std::cin>>val;
    std::cout<<"\n";
    SetX(val);
    }
    }

    dlclose(handle);
    return 0;
    }


    compile using

    g++ -fPIC -c getsetx.cpp
    ld -shared -o getsetx.so getsetx.o
    g++ -rdynamic -o test test.cpp -ldl

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...