10

I am trying to build and link a C++, cmake-based project with clang (3.0). This project links to several libraries that are installed in a custom directory /my/dir/. This directory is included in the LD_LIBRARY_PATH and LIBRARY_PATH environment variables. Project builds and links fine with g++.

The link command generated and executed by cmake looks like the following:

/usr/bin/clang++ -O3 stuff.cpp.o -o stuff -rdynamic -lmylib

ld then complains with the following message:

/usr/bin/ld: cannot find -lmylib

The link command above runs fine whenever I manually add -L/my/dir/. Is there a way to link without specifying the -L flag?

Régis B.
  • 10,092
  • 6
  • 54
  • 90
  • 5
    [`LD_LIBRARY_PATH`](http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html) is for loading libraries at startup, not for resolving link dependencies. Perhaps you want to use `LDFLAGS`? – Remus Rusanu Sep 25 '12 at 12:35
  • Interesting. I use __g++__ and __clang++__ interchangeably with CMake but never had a similar problem. I simply use the `link_directories()` macro to define the library path. – Hindol Sep 26 '12 at 05:43

1 Answers1

9

The $LD_LIBRARY_PATH environment variable (and its various alternatives on other UNIX-based platforms) is used at runtime, not link time, to find libraries.

Using -L is the correct approach and cannot be avoided.

Note: A better approach under Linux (you don't specify your platform so I'm guessing) is to correctly configure a file in /etc/ld.so.conf.d/ and avoid using $LD_LIBRARY_PATH altogether.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • 1
    Note that I also defined the LIBRARY_PATH variable. As explained in this question http://stackoverflow.com/questions/4250624/ld-library-path-vs-library-path this variable is what allows gcc to find the custom libraries. I am looking for something similar for clang. – Régis B. Sep 25 '12 at 12:54
  • @RégisB. Interesting; I've never used `LIBRARY_PATH`. What's the issue with using `-L`? – trojanfoe Sep 25 '12 at 12:58
  • 1
    The -L option requires a change in the cmake configuration, which is shared with my colleagues. I will now try going the /etc/ld.so.conf.d/ way. – Régis B. Sep 25 '12 at 13:04
  • 2
    @RégisB. The `/etc/ld.so.conf.d/` is *runtime* only as well; I mentioned it as it's a better approach than using `$LD_LIBRARY_PATH`; it won't affect your build. Why not add a custom variable to the cmake config that each of you can set to specify additional libraries during linking (if it's not set it does nothing and won't affect your colleagues) – trojanfoe Sep 25 '12 at 13:27