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.
3 Answers
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 19 Comments
a.out format so this is highly misleading. And why should you "never" create an executable called test?test is a system command. But since test programs usually never are installed in the system bin directory and require you to write ./test it is not that much a problem to me either...a.out format, but the name remains for legacy reasons. (And if you're incapable of using a shell properly then that's your problem; I for one know how to run an executable from the current directory. test is just fine for an executable name, as long as you're writing just a quick test snippet of course.)test is something that I have learned the hard way to regret and I am "perfectly capable of using a shell". It is a bad idea, and I've seen it bite many others who are "perfectly capable of using a shell".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 8 Comments
-lHeader instead of -llibHeader ?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 2 Comments
ranlib which in GNU simply means ar s.