6

According to this question, gcc's -l command requires your library to be named libXXX.a.

Is there a way to link a static library using a different command with gcc? The goal is to avoid this lib- prefix.

Community
  • 1
  • 1
GreySage
  • 1,153
  • 19
  • 39

2 Answers2

10

Just pass the library as in input file like so:

gcc main.c yourlibrary.a -o prog
  • 1
    To elaborate, `-l` is only needed to search the library path and automatically select a library with the standard naming pattern. – R.. GitHub STOP HELPING ICE Sep 01 '15 at 21:55
  • Accepted because it's the simplest implementation of the solution, even though Brian McFarland's answer is great too (and he taught me something about make files). – GreySage Sep 01 '15 at 21:56
5

Like nunzio said. Just pass it in directly as an input file. He beat me to it, but here's a full example anyway.

mylib.c:

#include <stdio.h>
void say_hi(void) 
{ 
  printf("hi\n"); 
}

main.c:

extern void say_hi(void);
int main(int argc, char**argv)
{
  say_hi();
  return 0;
}

Makefile:

main: main.c mylib.a
    gcc -o main main.c mylib.a

mylib.a: mylib.o
    ar rcs mylib.a mylib.o

mylib.o: mylib.c
    gcc -c -o $@ $^

I realize this assumes some background knowledge in Make. To do the same thing w/o make, run these commands in order:

gcc -c -o mylib.o mylib.c
ar rcs mylib.a mylib.o
gcc -o main main.c mylib.a
Brian McFarland
  • 9,052
  • 6
  • 38
  • 56
  • Forgive my newbishness, but can you explain your gcc -c -o $@ $^ command? – GreySage Sep 01 '15 at 21:48
  • 3
    Sure. It's a makefile thing, not a gcc thing. These are called automatic variables. `$@` represents the name of the make target. `$^` represents the prerequisites (i.e. dependencies) on the right side of the `:`. So in this case, it's short hand for `gcc -c -o mylib.o mylib.c`. Here it's not much use. I wrote this more out of habit than anything. But it's necessary for generic rules and can be useful otherwise. – Brian McFarland Sep 01 '15 at 21:53