I have two files -> fact.h and main.c in the /home/snyp1/new folder. main.c has the main function which calls the fact(int x) function in fact.h. I am creating a .a archive with the ar command ->
snyp1@Snyp:~/new$ ar -r -s libfact.a fact.o
ar: creating libfact.a
fact.h fact.o libfact.a main.c
snyp1@Snyp:~/new$ gcc main.c -L/home/snyp1/new -lfact -o main
/home/snyp1/new/libfact.a: could not read symbols: Archive has no index; run ranlib to add one
collect2: ld returned 1 exit status
snyp1@Snyp:~/new$ ranlib libfact.a
snyp1@Snyp:~/new$ gcc main.c -L/home/snyp1/new -lfact -o main
/home/snyp1/new/libfact.a: could not read symbols: Archive has no index; run ranlib to add one
collect2: ld returned 1 exit status
I am on ubuntu 12.04. Please let me know whats wrong. (Also, if I don't use the -L/.../new, gcc will say it can't find "lfact", maybe its because its not in /usr/local/lib)
EDIT: OK I have found the cause. Its due to the fact that I was using fact.h to build the fact.o and then putting it in the library, it wasn't working as expected. So I now changed it into file.c and is working fine now. I should have provided that information, I'm sorry. Though I don't know why this kind of problem should arise. Aren't libraries possible to make without at least one .c file in it?
Do you mean you were compiling
fact.hto producefact.o?If so, that wasn't doing what you expect. When you invoke
gccon a header file it produces a precompiled header, not an object file. So although you got a file calledfoo.oit wasn't a valid object file. If you had just rungcc -c fact.hit would have produced a precompiled headerfact.gch, but presumably you rangcc -c fact.h -o fact.owhich causes the file to be calledfact.oeven though it's still a precompiled header.file fact.owould have shown that:You could have forced GCC to treat the file as C code, not a header, by running
gcc -x c -c fact.h -o fact.o(the-x csays to treat the input as C code instead of inferring the type from the file extension) but it's probably simpler and less confusing to just name your file correctly instead of trying to compile a header.They need at least one object file (i.e.
.ofile) but you didn't have a valid object, you had a precompiled header misleadingly named as.o, but it was not actually an object file.The linker doesn't only look in
/usr/local/lib, there are other default places it looks, but yes, that's basically the problem. Note that you can also say-L.if the library is in the current directory, that's easier than giving an absolute path.