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 ...
- 06-13-2008 #1Just 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:
I made this file a shared library with this command:Code:#include <iostream> void print(char* message){ cout << message << endl; }
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++ -shared -Wl,-soname,libZACH.so.1 -o libZACH.so.1 foo.o -lc
The output I get from this command is:Code:g++ bar.cpp -LZach
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.Code:undefined reference to `print(char*)'
- 06-13-2008 #2
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


Reply With Quote