Note: I visited many topics with questions similar to this one, although solutions chosen as accepted were all things I've already tried, so please, consider this before marking as duplicate.

Also, I'm new to Linux in general, so feel free to correct me if I say something fundamentally incorrect.

The problem:

I'm trying to create and use a c++ shared library and while the "create" part seems to be done, while trying to link against it, ld cannot see it.

Here's what I've already managed to do:

  1. Compiled all .cpp files with -fPIC explicitly stated
  2. Created the library with

    g++ -shared -fPIC -Wl,-soname,libcustom_program_options.so.1 -o libcustom_program_options.so.1.0.1 *.o

  3. Ran ldconfig to update the loader cache like this:

    sudo ldconfig -n /usr/local/lib

And when I try to link the library against my test program:

g++ main.cpp -o main -L /usr/local/lib -l libcustom_program_options

Here's what happens:

/usr/bin/ld: cannot find -llibcustom_program_options

collect2: error: ld returned 1 exit status

Note: I wasn't sure if ld was looking for the library's full-name or soname or maybe the "name between lib- and .so.{version}", so I tried each one of those. Didn't help either.

  • Did you try -lcustom_program_options? the l is usually expanded to lib (so for example -lm links libm.so and so on) – steeldriver Mar 23 at 20:43
  • Yes, I did. By saying "name between lib- and .so.{version}" I meant exactly that: -lcustom_program_options. I think I tried all the possible combinations of syntaxes, to be honest. – TuRtoise Mar 25 at 10:45

Ok, I finally managed to solve it.

Once I checked what file the linker is actually expecting to find, I knew what to do next.

I did it by calling:

ld -L/usr/local/lib -lcustom_program_options --verbose

Where /usr/local/lib is the directory I put the library in, and custom_program_options is the name of the library stripped of the lib- prefix and all prefixes (i.e. extension and version).

As it printed a list of all considered directories along with the exact expected file name, I knew that it was looking for libcustom_program_options.so, whilst calling ldconfig (mentioned in the OP) set a link only between libcustom_program_options.so.1 and libcustom_program_options.so.1.0.1 (note the version number).

The file ld was trying to find indeed never existed.

The solution was to create the link manually:

sudo ln -s /usr/local/lib/libcustom_program_options.so.1 /usr/local/lib/libcustom_program_options.so

So this pretty much solved it. The culprit was me not knowing what was the exact filename sought by the linker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.