linuxx
linuxx

Reputation: 1527

How to create a static library with g++?

Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the .a? I would also like to know how can I compile a static library in and use it in other .cpp code. I have header.cpp, header.hpp . I would like to create header.a. Test the header.a in test.cpp. I am using g++ for compiling.

Upvotes: 132

Views: 182678

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

Compile your library into an object file using the command below
  g++ -c header.cpp

Create the archive:

  ar rvs header.a header.o

Test:

  g++ test.cpp header.a -o executable_name

Upvotes: 36

Sriram
Sriram

Reputation: 10578

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

Upvotes: 57

user2100815
user2100815

Reputation:

Create a .o file:

g++ -c header.cpp

add this file to a library, creating library if necessary:

ar rvs header.a header.o

use library:

g++ main.cpp header.a

Upvotes: 140

Related Questions