- //StaticMath.h
- #include <iostream>
- class StaticMath
- {
- public:
- //StaticMath(void);
- //~StaticMath(void);
- static double add(double a, double b);//加法
- void print();
- };
- //StaticMath.cpp
- #include "StaticMath.h"
- double StaticMath::add(double a, double b)
- {
- return a + b;
- }
- void StaticMath::print()
- {
- std::cout << "OK \n";
- }
- //TestStaticLibrary.cpp
- #include "StaticMath.h"
- #include <iostream>
- using namespace std;
- int main(int argc, char* argv[])
- {
- double a = 10;
- double b = 2;
- cout << "a + b = " << StaticMath::add(a, b) << endl;
- StaticMath sm;
- sm.print();
- return 0;
- }
- #1. 将代码文件编译成目标文件.o(StaticMath.o),注意带参数-c,否则直接编译为可执行文件。
- g++ -c StaticMath.cpp
- #2. 通过ar工具将目标文件打包成.a静态库文件。生成静态库libstaticmath.a。
- ar -crv libstaticmath.a StaticMath.o
- #3. Linux下使用静态库,只需要在编译的时候,指定静态库的搜索路径(-L选项)、指定静态库名(不需要lib前缀和.a后缀,-l选项)
- g++ TestStaticLibrary.cpp -L../StaticLibrary -lstaticmath
- #-L:表示要连接的库所在目录
- #-l:指定链接时需要的动态库,编译器查找动态连接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.a或.so来确定库的名称。
- 注:
来源: