8

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.

2 Answers 2

12

Just pass the library as in input file like so:

gcc main.c yourlibrary.a -o prog
Sign up to request clarification or add additional context in comments.

2 Comments

To elaborate, -l is only needed to search the library path and automatically select a library with the standard naming pattern.
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).
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

2 Comments

Forgive my newbishness, but can you explain your gcc -c -o $@ $^ command?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.