hi
I'm trying to compile an example from Stevens' apue book.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "apue.h"
#include <dirent.h>
int main(int argc,char *argv[]){
DIR *dp;
struct dirent *dirp;
if(argc!=2)
err_quit("usage: ls directory_name");
if((dp=opendir(argv[1]))==NULL)
err_sys("can't open %s",argv[1]);
while((dirp=readdir(dp))!=NULL)
printf("%s\n",dirp->d_name);
closedir(dp);
exit(0);
}
include/apue.h contains declarations of err_quit and err_sys and lib/error.c their definitions. The library is successfully compiled into lib/error.o and main program into ls1.o.
When I run gcc ls1.o lib/error.o -o ls1
or gcc lib/error.c ls1.c -Iinclude -o ls1
it compiles fine, but gcc -Llib/ -Iinclude ls1.c -o ls1
generates
/tmp/ccfva0gO.o: In function `main':
ls1.c:(.text+0x20): undefined reference to `err_quit'
ls1.c:(.text+0x5b): undefined reference to `err_sys'
collect2: ld returned 1 exit status
It looks like gcc ignores -L switch.
Am I doing something wrong?
I'm using gcc version 4.5.0 20100604 [gcc-4_5-branch revision 160292] (SUSE Linux) on openSUSE 11.3.
Thanks in advance
OK, I figured it out. There are 2 things I misunderstood about -L switch.
* -L is not enough, -l has to be used to specify which file to link. I wrongly assumed linker will search the directory for needed definitions.
* an object file can't be linked directly, it has to be part of the archive.
So, it would be: ar rcs lib/liberror.a lib/error.o
followed by gcc ls1.o -o ls1 -Llib/ -lerror
or gcc ls1.c -Iinclude/ -o ls1 -Llib/ -lerror
The irony is that I didn't notice that make already created lib/libapue.a with all object files. All I had to do is link it. Live and learn.
jsmith, thank you for the response
cheers