Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with ld and static library "undefined reference to"

This one is a little embarassing. I know what's going on but not why. I get an "undefined reference to" error which means the linker (ld) is not putting the code from the library I've created.

I'm currently fooling around with Zed A. Shaw "Learn C the Hard Way" course. I'm trying to finish exercise 32, but I keep getting the same error.

In the book you develop a make file that runs the following command:

cc -g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG  build/liblcthw.a \
    tests/list_tests.c   -o tests/list_tests

where -g is to enable debug info, -Wall is to enable "all" warnings, -Wextra is to enable more warnings, -Isrc to include src directory to the library directory, -o tests/list_tests is to produce an output with that name in that directory, -DNDEBUG to enable a variable from the code, -O2 for level 2 optimization (whatever that means) and build/liblcthw.a to include that library (the one that is getting build). The rest I have no clue what they do.

If I got it right there's a list.c in the src directory that creates an object list.o. This object is later include in the lib via ar and ranlib. So calling the header list.h should make ld to look in build/liblcthw.a for list.o. The thing is ld is not reading build/liblcthw.a for some reason. So i get this undefined reference to error.

I have tried to contact Zed but he's a busy man apparently. So I'm hoping to get help here. Tell me if i need to add more info about the issue. Here's a link to the whole library so far.

I hope someone can help me.

like image 328
Luciano Robino Avatar asked Feb 25 '13 03:02

Luciano Robino


1 Answers

Does the following work?

cc -g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG tests/list_tests.c \
   -o tests/list_tests -Lbuild -llcthw

What this does is using the -l option to link against the library, and the -L option to specify an additional directory where the linker should look for libraries. The lib prefix and .a suffix must not be specified in the -l argument.

Note that if you also have a shared library (*.so) in the "build" directory, things get complicated. To keep things simple, you should either delete the "liblcthw.so" file and only keep "liblcthw.a", or try to link-in the static library by listing it as an input, just like you did originally, but specifying it after your source file:

cc -g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG tests/list_tests.c \
   -o tests/list_tests build/liblcthw.a
like image 175
Nikos C. Avatar answered Oct 29 '22 19:10

Nikos C.