# 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
- gcc -c
- gcc -D
- gcc -g
- gcc -I
- gcc -o
- gcc -O
- gcc -Wall

### Write how to improve this page

| ×

| powered by |

##### GCC

- gcc -c
- gcc -D
- gcc -fPIC
- gcc -g
- gcc -I
- gcc -L -l
- gcc -o
- gcc -O
- gcc -Wall

##### RAPID TABLES

- Recommend Site
- Send Feedback
- About

#### Bookmark & Share

XClose AddThis Expanded Menu
Select from these web-based feed readers:
AOL
Bloglines
Google Reader
My MSN
Netvibes
Newsisfree
Pageflakes
Yahoo
Sharing Service Filter
No matching services.
Message sent! Share again.
Sending message...
AddThis
Bookmark & Share X

#### Make sharing easier with AddThis for Firefox.

Don't show these
Print
Gmail
Favorites
Reddit
Tumblr
More... (248)
AddThis