2

I am trying to compile code related to the book "Advanced Programming in the UNIX® Environment"

When I try to compile a test file like so:

$ gcc -L ../lib/ -l apue foo.c

I get:

/tmp/cccXkUae.o: In function `main':
foo.c:(.text+0x2b): undefined reference to `err_sys'
...
collect2: error: ld returned 1 exit status

However, it seems the function is defined in the lib...

$ grep err_sys ../lib/libapue.a 
Binary file ../lib/libapue.a matches

Ultimately, this does compile with no errors:

$ gcc foo.c ../lib/error.c

Just trying to understand what I am doing wrong.

mcede
  • 117
  • 5
  • 1
    Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – too honest for this site Sep 05 '16 at 16:42
  • 2
    On linker command lines, always put **libraries after object files** — always! – Jonathan Leffler Sep 05 '16 at 16:53
  • Thanks for helping out a noob, @JonathanLeffler; you are of course correct. Compiles just fine now. – mcede Sep 05 '16 at 21:18

2 Answers2

1

The source code available at http://www.apuebook.com/src.3e.tar.gz gets you (after building) a header named apue.h in include/ and a static lib named libapue.a in lib. So to compile and link against libapue, you need:

gcc -I $apue_root/include -L $apue_root/lib your_file.c -lapue
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Thanks @PSkocik. I had already compiled the static lib... I should have mentioned that. The problem I was having was related to the position of `-lapue` being behind my source file on the command line; your answer clearly demonstrates the correct format. – mcede Sep 05 '16 at 21:16
0

If you are linking with a static library (e.g. a *.a file on linux) then you can do compile your program like this:

gcc foo.c ../lib/libapue.a

If you want to link it with a dynamic (shared) library (e.g. a *.a file on linux) then you can use the command command that you suggested:

gcc -L../lib/ foo.c -lapue
redneb
  • 21,794
  • 6
  • 42
  • 54
  • It is better to get into the habit that always works — *libraries after object (or source) files*. On some systems, specifying a shared library before the object files does _not_ work; the library satisfies no undefined symbols at the time, so it isn't looked at later after the object files have been scanned. – Jonathan Leffler Sep 05 '16 at 21:21