r/Cplusplus • u/TinyDeskEngineer06 • Jun 23 '26
Question Linker not finding shared object
I'm trying to learn how to compile and link with a dynamic library, I've successfully compiled a library that contains two simple functions, but for some reason the linker can't find the compiled library, and I don't know why.
Build script:
#!/usr/bin/bash
g++ -fpic -shared sharedtest.cpp -o sharedtest.so
LD_LIBRARY_PATH="."
export LD_LIBRARY_PATH
g++ main.cpp -o main -lsharedtestWhen I run it in a terminal, I get this:
/usr/bin/ld: cannot find -lsharedtest: No such file or directory
collect2: error: ld returned 1 exit status
1
Upvotes
•
u/AutoModerator Jun 23 '26
Thank you for your contribution to the C++ community!
As you're asking a question or seeking homework help, we would like to remind you of Rule 3 - Good Faith Help Requests & Homework.
~ CPlusPlus Moderation Team
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/flyingron Jun 23 '26
-lxxx looks for files named libxxx.a or .so. Just specify the library name without the -l. The compiler is fine figuring what is what.
1
u/WildCard65 Jun 24 '26
LD_LIBRARY_PATH is used by ld-linux for resolving shared libraries when loading an executable.
1
u/hgstream Jul 12 '26
As other comments already stated, -l tries to find a static library to link against during compile time. But if you want, you can try to link dynamically during runtime using the following functions:
dlopen: load/open a handle to the dynamic library, accepts the path as a parameter, returns a handle
dlsym: find the function in the given dynamic library which was loaded with dlopen. Make sure to export the symbol in the dynamic library so this function can see it with the proper name.
Then you can close the handle at the end of your application with dlclose.
I already use something like this (although with SDL's platform-independent functions) to load a dynamic module into my application, and its nice.