To build the static library, select Build > Build Solution on the menu bar. The build creates a static library, MathLibrary. lib, that can be used by other programs.
In other words, the “ar” command can be used to create a static library, to add and to modify object files already included in the library.
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
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
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 the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With