MaximV
MaximV

Reputation: 315

How do you link a C++ library from the command line

I am making C++ library that has multiple headers (all headers having a .h, .cpp, and .o file), how do I make the library linkable so that the user can compile it like: g++ main.cpp -o binaries -l libraryName?

Upvotes: 0

Views: 845

Answers (1)

Employed Russian
Employed Russian

Reputation: 213636

how do I make the library linkable

Like so:

ar ruv libraryName.a foo.o bar.o baz.o

This is best achieved by writing a Makefile, which will automate the build process for you. Something like this:

all: libraryName.a
clean:
        rm -f *.o  # important: use TAB, not spaces for indentation here.

SRCS = foo.cpp bar.cpp baz.cpp
OBJS = ${SRCS:.cpp=.o}

libraryName.a: ${OBJS}

P.S. To use libraryName.a, do this:

g++ -o exename main.cpp -lbraryName

and not this (requires library named liblibraryName):

g++ -o exename main.cpp -l libraryName

Upvotes: 1

Related Questions