'Attempting to compile with my own static C library

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community