In another thread I mentioned my Sudoku game. I'm trying to get it to work in Linux. After some lengthy effort I'm getting some errors. In the game. generator.so is loaded, but I can't extract the functions.
After some work, I've made a simple test program and can't get the so to load.
// yeah.cpp #include <stdio.h> int p = 0; int yeah() { printf( "%d\n", ++p ); return 0; }
Compiled with:
g++ -o yeah.so -shared -fPIC yeah.cpp
1 | // main.cpp |
2 | #include <stdio.h> |
3 | #include <stdlib.h> |
4 | #include <dlfcn.h> |
5 | |
6 | int main( int argc, char **argv ) |
7 | { |
8 | int rt = 0; |
9 | const char modName[ 40 ] = "yeah.so"; |
10 | void *library = NULL; |
11 | int (*yeah)() = NULL; |
12 | |
13 | |
14 | if ( !( library = dlopen( modName, RTLD_LAZY) ) ) |
15 | { |
16 | printf( "Could not load: %s\n", modName ); |
17 | return -1; |
18 | } |
19 | |
20 | yeah = (int (*)())dlsym( library, "yeah"); |
21 | |
22 | if ( !yeah ) |
23 | { |
24 | printf( "Could not extract function\n" ); |
25 | return -2; |
26 | } |
27 | |
28 | for ( int i = 0; i < 5; i++ ) |
29 | { |
30 | yeah(); |
31 | } |
32 | |
33 | dlclose(library); |
34 | |
35 | return 0; |
36 | } |
Compiled with:
g++ -o main main.cpp -ldl
yeah.so and main are created with permissions 777. But when main is ran as
./main, I get the 'Could not load: yeah.so'
So, what am I doing wrong? Any suggestions to help me.
Set your LDPATH (or was it LD_PATH?) to point to the directory where the .so file is. Otherwise, add it to /etc/ld.so.conf (or something similar) and run ldconfig. Or run ldconfig dir/where/so/is to temporarily add it to your linker path.
No, use absolute paths! For example:
char soName[] = "yeah.so" char fullName[MAX_PATH]; replace_filename(fullName, argv[0], soName, MAX_PATH); ...
ReyBrujo: That's for dynamically loading plugins!
EDIT: Hmm, still doesn't work. Interesting, because I use very similar code and it works...
Oh, you are right. With the full path it loads the library but can't get the handle to the function.
(Edited: Got it working. The problem is that the function name is mangled in C++, thus you can't just load yeah, but instead _Z4yeahv (in my case). Some magic with extern "C" should make it work.
Set your LDPATH (or was it LD_PATH?)
LD_LIBRARY_PATH
Oh I forgot he didn't have extern "C".
So, final solution:
1. extern "C" in front of the functions you export
2. load .so with full path
Ok I did that and the program runs fine. It wasn't loading the text correctly, but I fixed that also. I just need to compile it statically and add it to the download page.
Thanks Guys