Aman Deep Gautam
Aman Deep Gautam

Reputation: 8747

Which linker options to include gcc

I compile a project and run it on my system, it does perfectly fine.

I uploaded this to git and asked my administrator to run it on server and it says undefined reference to 'clock_gettime'. This error can be resolved by linking a library with -lrt option. Similar problem happened to me earlier but that was related to linking math.h library with the help of -lm option.

Is there a way to find which all libraries to link so that ou do not run into such problems and not feel embarrassed in front of your administrator. How to decide what all libraries to link. Can there be a thought process for this?

Upvotes: 2

Views: 1069

Answers (2)

Kevin Grant
Kevin Grant

Reputation: 5431

Some man pages will mention both the headers and libraries that should be used. (This is not true of all pages unfortunately.)

For example, look at man 3 signal. On my system that page has a LIBRARY section at the top with Standard C Library (libc, -lc), followed by a SYNOPSIS section with #include <signal.h>.

Some other strategies include:

  • Blunt use of strings piped to egrep in a shell loop, to search for references to names among installed libraries. This can return a lot of false positives for common names, but it works very well for elaborate function names that don't match single English words.

  • Iterative compilation and linking. If you are trying to resolve a single function, write a tiny program that calls the function and use a shell or makefile loop to test each single library on your system (starting with a small list of most likely candidates from /usr/lib or wherever else). At some point the build will succeed and show you the right library. This method takes a little work to set up, but the infrastructure you create is also very easy to reuse in the future.

  • Inspect binaries iteratively using your linker's tools (e.g. otool on Mac OS X, or objdump or readelf on Solaris or Linux). For instance, try to disassemble a library's text section starting from a particular name (otool -v -t -p _symbol on Mac OS X).

Upvotes: 1

Michael Boselowitz
Michael Boselowitz

Reputation: 3006

For *nix based machines, ldd on the executable will print shared library dependencies.

Upvotes: 1

Related Questions