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?
I was using fact.h to build the fact.o and then putting it in the library, it wasn't working as expected.
Do you mean you were compiling fact.h
to produce fact.o
?
If so, that wasn't doing what you expect. When you invoke gcc
on a header file it produces a precompiled header, not an object file. So although you got a file called foo.o
it wasn't a valid object file. If you had just run gcc -c fact.h
it would have produced a precompiled header fact.gch
, but presumably you ran gcc -c fact.h -o fact.o
which causes the file to be called fact.o
even though it's still a precompiled header. file fact.o
would have shown that:
$ file fact.o
fact.o: GCC precompiled header (version 013) for C
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 c
says 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.
Aren't libraries possible to make without at least one .c file in it?
They need at least one object file (i.e. .o
file) 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.
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
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.