Imagine that you have written a calculator program in C++ that performs addition, subtraction, multiplication, and division, and the entire program sits in a single source file. Your first version might look like this.
Example 1: calculator_solution.cpp, a complete calculator program in one source file
<iostream>int add(int x, int y){ return x + y;}int subtract(int x, int y){ return x - y;}int divide(int x, int y){ if (y == 0) { std::cerr << "Error: Division by zero!\n"; return 0; } return x / y;}int multiply(int x, int y){ return x * y;}int main(){ int a = 10; int b = 5; std::cout << "Addition: " << add(a, b) << '\n'; std::cout << "Subtraction: " << subtract(a, b) << '\n'; std::cout << "Multiplication: " << multiply(a, b) << '\n'; std::cout << "Division: " << divide(a, b) << '\n'; return 0;}
Compile the program with GCC:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ calculator_solution.cpp -o calculator_solution
Run the executable:
./calculator_solution
The program produces the following output:
Addition: 15Subtraction: 5Multiplication: 50Division: 2
A client wants to use your calculator
You then find a client who is interested in buying your calculator solution for their own purposes. Your first thought may be to give them the calculator_solution executable. That executable, however, is a finished program. It starts from your main() function, uses the values you selected and displays the output in the format you defined.
The client is interested only in the calculator part of the solution. They already have their own application and want to use your add(), subtract(), multiply(), and divide() functions inside it. What they need is a reusable component that their own build can pull in, so that the four functions end up as part of their program. A finished executable cannot do that job, because it can only be launched and run; it does not offer its individual functions to any other program that wants to call them.
Separating the calculator from the application
The original source file contains two different responsibilities:
- The calculator functions perform the reusable calculations.
main()contains the application logic that decides how those functions are used.
The first improvement is to separate them. Move the calculator functions into calculator.cpp and keep the application logic in main.cpp.
The project now has this structure:
calculator/├── calculator.cpp└── main.cpp
Creating the reusable calculator component
Move the calculator functions into their own source file.
Example 2: calculator.cpp, the reusable calculator implementation
<iostream>int add(int x, int y){ return x + y;}int subtract(int x, int y){ return x - y;}int divide(int x, int y){ if (y == 0) { std::cerr << "Error: Division by zero!\n"; return 0; } return x / y;}int multiply(int x, int y){ return x * y;}
This file now contains only the calculator implementation. It does not contain main() and is therefore not a complete application by itself.
Keeping the application logic in main.cpp
The application remains in main.cpp. At this stage, the calculator function declarations are written directly in the application file so that the compiler knows how each function can be called.
Example 3: main.cpp, the application using the separated calculator functions
<iostream>int add(int x, int y);int subtract(int x, int y);int divide(int x, int y);int multiply(int x, int y);int main(){ int a = 10; int b = 5; std::cout << "Addition: " << add(a, b) << '\n'; std::cout << "Subtraction: " << subtract(a, b) << '\n'; std::cout << "Multiplication: " << multiply(a, b) << '\n'; std::cout << "Division: " << divide(a, b) << '\n'; return 0;}
The declarations tell the compiler the names, return types and parameter types of the calculator functions. Their definitions remain in calculator.cpp.
Compile and link the two source files:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ main.cpp calculator.cpp -o calculator_application
The program still produces the same result:
Addition: 15Subtraction: 5Multiplication: 50Division: 2
You have now separated the reusable calculator component from the application logic. The application decides how the calculator is used, while calculator.cpp provides the calculations.
But how do you deliver it to the client?
The source-code separation improves the structure of your program, but it does not solve the delivery problem.
You could give the client calculator.cpp. They could compile it with their application:
g++ -std=c++17 client_application.cpp calculator.cpp \ -o client_application
Technically, this works. The client receives the calculator implementation, compiles it and links it into their program.
But are you ready to give them the complete source code?
The calculator example contains only a few arithmetic operations. A commercial implementation could contain an algorithm developed through years of research, experimentation, testing, and optimization. That implementation may be the main intellectual property behind your solution.
The price agreed with the client covers the right to use the calculator component. Access to the implementation source, along with the right to modify it or pass it on to others, is normally a separate agreement carrying a separate price.
Fortunately, the client has already said that they are happy to receive the calculator in whatever reusable form suits you, so long as they can call it from their application.
So what can you give them instead of calculator.cpp?
They need two things.
- The first is a description of the calculator functions they can call, giving the name, the parameter types and the return type of each one, so that their compiler knows how to generate a call.
- The second is the compiled machine code for those functions, so that the linker can resolve those calls and place the working code into their program.
This is where the concepts of a public interface and a static library come inseful.
Creating a public interface
When the client calls a function such as add() or divide(), the compiler must know that the function exists. It must also know the function’s return type and parameter types.
The compiler does not need the function body to compile the call. A declaration is enough because it tells the compiler how to check the arguments and determines the type of the call expression. Later, the linker must find the compiled definition of that function.
You can place the function declarations, also called function prototypes, in a header file, separate from their definitions.
Example 4: calculator.h, the public interface of the calculator component
CALCULATOR_H CALCULATOR_Hint add(int x, int y);int subtract(int x, int y);int divide(int x, int y);int multiply(int x, int y);
This header is the public interface of the calculator component. It tells the client which operations are available and how to call them. For example, the following declaration tells the compiler that add() accepts two int arguments and returns an int:
int add(int x, int y);
However, it does not reveal how the addition is implemented. The include guard prevents the header contents from being processed more than once in the same translation unit.
Using the interface from the application
The application can now include calculator.h instead of repeating the declarations.
Example 5: main.cpp, the application using the public calculator interface
"calculator.h" <iostream>int main(){ int a = 10; int b = 5; std::cout << "Addition: " << add(a, b) << '\n'; std::cout << "Subtraction: " << subtract(a, b) << '\n'; std::cout << "Multiplication: " << multiply(a, b) << '\n'; std::cout << "Division: " << divide(a, b) << '\n'; return 0;}
Checking the implementation against the interface
The definitions of the calculator functions go into a .cpp file. The implementation file should include the same public header.
Example 6: calculator.cpp, the implementation checked against the public interface
"calculator.h" <iostream>int add(int x, int y){ return x + y;}int subtract(int x, int y){ return x - y;}int divide(int x, int y){ if (y == 0) { std::cerr << "Error: Division by zero!\n"; return 0; } return x / y;}int multiply(int x, int y){ return x * y;}
Including calculator.h in calculator.cpp allows the compiler to check the definitions against the public declarations. For example, if the header declares add(int, int) but the implementation defines a different parameter type, the mismatch will be detected during compilation.
You can now give calculator.h to the client. However, the header contains declarations only. The client still needs the compiled definitions when linking the application. This is where the static library comes in.
What is a static library?
A static library is an archive containing one or more compiled object files. On Linux, a conventional static-library filename has this form:
lib<library_name>.a
For a library named calculator, the filename is:
libcalculator.a
The library will contain the compiled implementation from calculator.cpp. The client can link the library into their application without receiving the original .cpp file.
The planned delivery package now looks like this:
calculator_package/├── include/│ └── calculator.h└── lib/ └── libcalculator.a
The header is used during compilation. The static library is used during linking.
Compiling the calculator implementation
Before creating the library, compile calculator.cpp into an object file:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ -c calculator.cpp -o calculator.o
The -c option tells g++ to compile the source file without running the linker. The result is:
calculator.o
calculator.o contains relocatable machine code and symbol information for the calculator functions. It is not an executable because it does not contain main() and has not been linked into a complete program. You could give the object file directly to the client, but a static library is the usual way to package one or more related object files under a single library name.
Creating the static library
Use GNU ar to package calculator.o into a static library:
ar rcs libcalculator.a calculator.o
The option letters have separate meanings:
raddscalculator.oor replaces an existing archive member with the same name.ccreates the archive if it does not already exist and suppresses the normal archive-creation warning.screates or updates the archive’s symbol index, which helps the linker locate definitions.
The command produces:
libcalculator.a
You now have the public interface in calculator.h and the compiled implementation in libcalculator.a.
Inspecting the static library
Use ar to list the object files stored in the archive:
ar t libcalculator.a
The output shows the archive member:
calculator.o
You can also inspect the defined C++ symbols with nm:
nm -C --defined-only libcalculator.a
The -C option demangles C++ symbol names, making names such as add(int, int) readable.
The output includes definitions for the four calculator functions. Exact addresses and compiler-generated symbols depend on the compiler and target platform.
A static library is a binary archive, so sending its raw contents to the terminal produces unreadable output. So, do not use something like cat to inspect libcalculator.a.
Testing the static library
Before sending the library to the client, compile the application separately:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ -c main.cpp -o main.o
The compiler uses calculator.h to check the function calls. Because -c is specified, this command does not attempt to resolve the function definitions.
Link main.o with the calculator library:
g++ main.o -L. -lcalculator -o calculator_application
Each part of the command has a specific purpose:
main.ocontains the compiled application code and references to the calculator functions.-L.adds the current directory to the library search path.-lcalculatortells the linker to search for the library namedcalculator.-o calculator_applicationspecifies the output executable name.
With the static archive available in the current directory, -lcalculator finds libcalculator.a. The position of the library in the command is important. The GNU linker processes object files and libraries in command-line order. main.o appears before -lcalculator so that the unresolved calculator references are already known when the archive is searched. Run the application:
./calculator_application
The output remains the same:
Addition: 15Subtraction: 5Multiplication: 50Division: 2
The test confirms that the application can use the calculator functions through the public header and static library without compiling calculator.cpp as part of the application build.
Preparing the customer package
Create separate directories for the public header and compiled library:
mkdir -p calculator_package/includemkdir -p calculator_package/lib
Copy the header and static library into the package:
cp calculator.h calculator_package/include/cp libcalculator.a calculator_package/lib/
The completed package contains:
calculator_package/├── include/│ └── calculator.h└── lib/ └── libcalculator.a
The client receives these two files:
calculator.h, which describes the public interfacelibcalculator.a, which contains the compiled implementation
You retain:
calculator.cpp
The client can use your calculator functions without receiving the original implementation source. The header and static library must be delivered as a matching pair. If the declarations in calculator.h do not match the definitions compiled into libcalculator.a, the client may encounter compilation errors, linker errors or binary incompatibility.
Building the client’s application
Suppose the client has written an application named client_application.cpp. It includes the supplied calculator header:
"calculator.h"
The client first compiles the application using the supplied include directory:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ -Icalculator_package/include \ -c client_application.cpp -o client_application.o
The -Icalculator_package/include option tells the compiler where to find calculator.h.
The client then links the application object file with your static library:
g++ client_application.o \ -Lcalculator_package/lib \ -lcalculator \ -o client_application
The library-related options have different purposes:
-Lcalculator_package/libtells the linker where to search for libraries.-lcalculatortells the linker which library to use.
The client can now run the application:
./client_application
Their application uses the compiled calculator implementation without requiring calculator.cpp.
Why both files must be delivered
The client needs both calculator.h and libcalculator.a.
If you provide only the static library, compilation fails when the application tries to include the missing header:
fatal error: calculator.h: No such file or directory
If you provide only the header, the application can be compiled into an object file, but the final link fails because the calculator function definitions are missing. The header answers the compiler’s question:
How can these functions be called?
The static library answers the linker’s question:
Where are these functions defined?
A usable library delivery therefore requires the public interface and the matching compiled implementation.
Why the lib prefix matters
Suppose you create the archive with this filename:
ar rcs calculator.a calculator.o
You then try to link it using:
g++ main.o -L. -lcalculator -o calculator_application
The linker does not find calculator.a through the normal -lcalculator naming convention. For this command, the expected static-library filename is:
libcalculator.a
Create the archive with the conventional name:
ar rcs libcalculator.a calculator.o
GNU ld also supports an exact filename form such as:
g++ main.o -L. -l:calculator.a -o calculator_application
Using libcalculator.a with -lcalculator follows the usual library naming convention and keeps the build commands familiar.
Does the application need the library at runtime?
The client needs libcalculator.a while linking the application. After the executable has been created, the calculator archive is not loaded as a separate runtime library.
The linker extracts the required archive member and uses its object code while constructing the executable. The resulting application can run without libcalculator.a being present on the target system.
This does not mean that the entire executable is statically linked. The program may still depend on shared system libraries and the shared C++ runtime. Statically linking your calculator library does not automatically make every dependency static.
The complete build sequence
The supplier’s complete build sequence is:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ -c calculator.cpp -o calculator.oar rcs libcalculator.a calculator.og++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ -c main.cpp -o main.og++ main.o -L. -lcalculator -o calculator_application./calculator_application
The customer receives:
calculator_package/├── include/│ └── calculator.h└── lib/ └── libcalculator.a
They compile and link their application with:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror \ -Icalculator_package/include \ -c client_application.cpp -o client_application.og++ client_application.o \ -Lcalculator_package/lib \ -lcalculator \ -o client_application
The calculator began as part of a complete program. Separating calculator.cpp from main.cpp made it reusable within the source tree. Introducing calculator.h created a public interface. Packaging the compiled implementation as libcalculator.a then made it possible to deliver that reusable component without supplying calculator.cpp.
Discover more from Tech For Talk
Subscribe to get the latest posts sent to your email.

Leave a Reply