Question

I'm trying to figure out how to use static libraries, but the most trivial example fails:

//foo.c
int func(int i) {
  return i+1;
}
//main.c
int func(int i);
int main() {
  return func(41);
}

Compiling foo.c and main.c works:

gcc -Wall -o foo.o -c foo.c
gcc -Wall -o main.o -c main.c

Archiving foo.o does not complain either:

ar rcs libfoo.a foo.o

But Linking fails with an undefined reference to func:

ld libfoo.a main.o
ld -L. -lfoo main.o

both give me:

ld: warning: cannot find entry symbol _start; defaulting to 00000000004000b0
main.o: In function `main':
main.c:(.text+0xa): undefined reference to `func'

I get a similar error if I take the detour via gcc to link:

gcc libfoo.a main.o
gcc -L. -lfoo main.o

give me:

main.o: In function `main':
main.c:(.text+0xa): undefined reference to `func'
collect2: ld returned 1 exit status

What am I doing wrong here? According to all manuals and search engines I read/used this is the way to use static libraries.


Edit: Mind that gcc foo.o main.o works perfectly fine.

Was it helpful?

Solution

After a lot of trying stupid stuff, the most stupid idea was the solution: ld wants the object files first, then the archives. Yay!

gcc libfoo.a main.o  // fails
gcc main.o libfoo.a  // works

The same goes if you specify the library with -L. and -lfoo: Where you put -L doesn't matter apparently, but where you put -lfoo matters to the same extent as if you specify the .a file directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top