gcc -L / -l option flags


gcc -l links with a library file.

gcc -L looks in directory for library files.

Syntax

$ gcc [options] [source files] [object files] [-Ldir] -llibname [-o outfile]

 

Link -l with library name without the lib prefix and the .a or .so extensions.

Examples

Example1

For static library file libmath.a use -lmath:

$ gcc -static myfile.c -lmath -o myfile

 
Example2

For shared library file libmath.so use -lmath:

$ gcc myfile.c -lmath -o myfile

 
Example3

file1.c:

// file1.c
#include <stdio.h>

void main()
{
    printf("main() run!\n");
    myfunc();
}

 

file2.c:

// file2.c
#include <stdio.h>

void myfunc()
{
    printf("myfunc() run!\n");
}

 

Build file2.c, copy object file file2.o to libs directory and archive it to static library libmylib.a:

$ gcc -c file2.c
$ mkdir libs
$ cp file2.o libs
$ cd libs
$ ar rcs libmylib.a file2.o

 

Build file1.c with static library libmylib.a in libs directory.

Build without -L results with an error:

$ gcc file1.c -lmylib -o outfile
/usr/bin/ld: cannot find -llibs
collect2: ld returned 1 exit status
$

Build with -L and run:

$ gcc file1.c -Llibs -lmylib -o outfile
$ ./outfile
main() run!
myfunc() run!
$

 


See also

GCC
CONTACT