- 目录结构如下:
root@ubuntu:/home/aaa/makeTest# ls -l
total 12
-rw-r--r-- 1 root root 127 Sep 24 19:09 main.cpp
-rw-r--r-- 1 root root 99 Sep 24 19:18 test.cpp
-rw-r--r-- 1 root root 28 Sep 24 19:11 test.h
- 将test.cpp编译为目标文件,将会生成test.o文件。
g++ -c test.cpp
- 将 test.o文件打包为静态库文件。
ar -cr libtest.a test.o
- 生成可执行文件。
g++ -o main main.cpp -L. -ltest
注意:
生成和使用库文件时文件名必须符合规范,静态库文件的命令为:lib+库名称+.a,使用时-l选项后面只需要跟库名即可,不需要前缀lib和后缀.a,否则会报错。