4

I compiled a static library. I have two files.

  • mylib_1.c with function foo1 in it
  • mylib_2.c with function foo2 in it.

Both #include "mylib.h".

I compiled a library like so:

gcc -c mylib_1.c -o mylib_1.o
gcc -c mylib_2.c -o mylib_2.o
ar cr mylib.a mylib_1.o mylib_2.o

Then I tried to compile mylib_test.c with my library.

#include "mylib.h"

int main(void)
{
    foo1("do something cool");
    foo2("do something cool");

    return 0;
}

If I compile like gcc mylib_test.c mylib.a, GCC succeeds and everything works fine.

If I compile like gcc mylib_test.c -Lmylib.a, GCC fails with:

C:\path\to\mylib_test.c:x: undefined reference to foo1
C:\path\to\mylib_test.c:x: undefined reference to foo2

Why does GCC fail?

If it makes a difference, I'm running the latest version of MinGW on Windows 7.1.

veryreverie
  • 2,871
  • 2
  • 13
  • 26
DEADBEEF
  • 525
  • 1
  • 5
  • 19

1 Answers1

6

You probably want the -l flag instead of the -L flag for gcc. -L adds library paths, whereas -l links to the library.

Also, if you are making that static library for Linux, its name should begin with lib (but does not have to, thanks to @davmac for mentioning). So your library's file name should be libmyLib.a, and then you should link against it with -lmyLib. (Yes, I find that awkward too.).

I don't know about Windows, but I guess the Windows static library's equivalent is simply myLib.lib. Please verify this statement first if you are making a Windows library.

See more here.

Community
  • 1
  • 1
adentinger
  • 1,367
  • 1
  • 14
  • 30
  • 1
    "its name must begin with lib" - [not necessarily!](http://stackoverflow.com/questions/10234208/how-do-i-link-a-library-file-in-gcc-that-does-not-start-with-lib) :) – davmac Mar 08 '17 at 23:07
  • @davmac Excellent! I'll wake up tomorrow less unintelligent. – adentinger Mar 08 '17 at 23:10
  • Thanks. Had to move the `.a` into `MinGW\lib`, but otherwise, this was the answer. – DEADBEEF Mar 09 '17 at 03:41
  • 1
    @Lͬͬ̓̈́ͧͣ̽Oͭ̇͂͋̊̆͑ͧ͆͆ͫͬLͣͩ͗̾͐̚ to avoid needing to move your archive you likely need to specify _both_ the library path and the library to link against: `-L. -l:mylib.a` – davmac Mar 09 '17 at 14:54
  • 1
    Great link, btw! – DEADBEEF Mar 10 '17 at 19:17