UNIX & GNU/Linux - gcc - Option -L for adding libraries during linking

We can add libraries during the linking step.
This tutorial is the same for g++ of course.

We use for that the -L option and add just after (without any space) the path of the libraries.
Libraries are generally prefixed with "lib" and suffixed with the .a extension.

Let's suppose we previously created a library named libgreatone.a in /soft/personal/lib.
We have so: /soft/personal/lib/libgreatone.a.

OK, to call this lib, we have first to specify the path and then the name of this library witout the prefix "lib".
For the first step, let's use the -L option and for the second one use the -l (an "L" lowercase).
Notice that there is no space after the -L nor the -l option.

We have so a linking line just like that:

gcc -o myProg main.o -L"/soft/personal/lib" -lgreatone

And with a Makefile:

## BadproG.com
## Makefile

## Variables
NAME            = myProg
SRC                = main.c
OBJ                = $(SRC:.c=.o)
LIBS            = -L"/soft/personal/lib"
CPPFLAGS    = -Wall -Werror -Wextra -pedantic -ansi
LDFLAGS        =  $(LIBS) -lgreatone
CC        = gcc

## Rules
$(NAME) : $(OBJ)
    $(CC) $(OBJ) -o $(NAME) $(LDFLAGS)
all     : $(NAME)
clean   :
    rm -f $(OBJ)
fclean  : clean
    rm -f $(NAME)
re    : fclean all
r    : re
    rm -f *~
    rm -f *.o

A great way to call libraries of our choice. wink

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.