Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include static library in makefile

Tags:

c

linux

gcc

x86-64

I have the following makefile

CXXFILES = pthreads.cpp   CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine LIBS = -lpthread -ldl  all:     $(CXX) $(CXXFILES) $(LIBS) $(CXXFLAGS)  clean:     rm -f prog *.o 

I am trying to include the ./libmine library within CXXFLAGS, but it seems like it is not the right way to include a static library, because when I compile the program, I get many undefined references error. So what is actually the right way to include a static library in the makefile?

like image 444
pythonic Avatar asked Jul 05 '12 13:07

pythonic


People also ask

How do I create a static library in makefile?

First, create a makefile in the directory where you want your static library to be created, and declare a phony target all whose single prerequisite is the static library. Next, declare your static library target.

What is libs in makefile?

The -L option specifies a directory to be searched for libraries (static or shared).

What is $@ in makefile?

The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.


2 Answers

use

LDFLAGS= -L<Directory where the library resides> -l<library name> 

Like :

LDFLAGS = -L. -lmine 

for ensuring static compilation you can also add

LDFLAGS = -static 

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a 
like image 85
Aftnix Avatar answered Oct 04 '22 11:10

Aftnix


CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine LIBS = libmine.a -lpthread  
like image 39
ouah Avatar answered Oct 04 '22 10:10

ouah