When creating a static library with g++, you need to follow these steps: writing source code, compiling source code into object files, and using the ar command to create the static library. Below are the detailed steps and examples:
Step 1: Write Source Code
First, write your source code. Assume we have two source files: file1.cpp and file2.cpp.
file1.cpp
cpp// file1.cpp #include "file1.h" int add(int a, int b) { return a + b; }
file1.h
cpp// file1.h #ifndef FILE1_H #define FILE1_H int add(int a, int b); #endif
file2.cpp
cpp// file2.cpp #include "file2.h" int multiply(int a, int b) { return a * b; }
file2.h
cpp// file2.h #ifndef FILE2_H #define FILE2_H int multiply(int a, int b); #endif
Step 2: Compile Source Code to Object Files
Use g++ to compile each source file into object files (.o files):
bashg++ -c file1.cpp -o file1.o g++ -c file2.cpp -o file2.o
The -c flag tells g++ to generate only object files without linking.
Step 3: Use the ar Command to Create a Static Library
Use the ar command to create a static library file. ar is a tool used for creating, modifying, and extracting files from archives, which is suitable for static library management.
bashar rcs libmystaticlib.a file1.o file2.o
The rcs option for the ar command:
r: replaces existing files.c: creates a new archive file.s: creates an index (or symbol table) for the library file, which helps the linker optimize lookup during linking.
The generated libmystaticlib.a is your static library file.
Step 4: Compile a Program Using the Static Library
Now, use this static library to compile and link other programs. Assume you have a main.cpp file:
main.cpp
cpp#include "file1.h" #include "file2.h" #include <iostream> int main() { std::cout << "3 + 4 = " << add(3, 4) << std::endl; std::cout << "3 * 4 = " << multiply(3, 4) << std::endl; return 0; }
Compile and link with the following command:
bashg++ main.cpp -L. -lmystaticlib -o myprogram
The -L. option tells the compiler to search for library files in the current directory, while -lmystaticlib links the created libmystaticlib.a static library.
After performing these steps, you have successfully created a static library using g++ and compiled a program using this static library. This allows you to effectively reuse your code and share the same implementation across multiple programs.