静态库
目录:
(base) ubuntu@VM-8-7-ubuntu:~/cppproject/codeso$ tree ../code
../code
├── hello.cpp
├── hello.h
├── hello.o
├── libhello.a
├── main
└── main.cpp
0 directories, 6 files
hello.cpp
#include "hello.h"
void Hello()
{ printf("Hello World!!!\n");}
hello.h
#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>
void Hello();
#endif
main.cpp
#include "hello.h"
int main(void){
Hello();
return 0;
}
编译脚本
g++ -c hello.cpp # 编译生成 hello.o
ar cr libhello.a hello.o # 生成静态库文件
g++ -o main main.cpp -static -lhello -L. # 链接生成可执行文件
关于链接生成可执行文件的参数
g++ -o main main.cpp -static -lhello
/usr/bin/ld: cannot find -lhello
collect2: error: ld returned 1 exit status
-L参数指定了,额外的库文件搜索路径
动态库
(base) ubuntu@VM-8-7-ubuntu:~/cppproject/codeso$ tree .
.
├── hello.cpp
├── hello.h
├── hello.o
├── libhello.so
├── main
└── main.cpp
0 directories, 6 files
hello.cpp
#include "hello.h"
void Hello()
{ printf("Hello World!!!\n");}
hello.h
#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>
void Hello();
#endif
main.cpp
#include "hello.h"
int main(void){
Hello();
return 0;
}
编译脚本
g++ -c fPIC hello.cpp -o hello.o # 编译生成 hello.o
g++ -shared hello.o -o libhello.so # 生成动态库文件
g++ -o main main.cpp -lhello -L. -Wl,-rpath=$(pwd) # 链接生成可执行文件
cmake创建动态库
(base) ubuntu@VM-8-7-ubuntu:~/cppproject/codecmake$ tree .
.
├── codecmakelib
│ ├── build
│ ├── CMakeLists.txt
│ └── lib
│ ├── CMakeLists.txt
│ ├── hello.cpp
│ ├── hello.h
│ └── libhello.so
└── codecmakesrc
├── build
├── CMakeLists.txt
└── src
├── CMakeLists.txt
└── main.cpp
/home/ubuntu/cppproject/codecmake/codecmakelib/CMakeLists.txt
PROJECT(HELLOLIB)
ADD_SUBDIRECTORY(lib)
/home/ubuntu/cppproject/codecmake/codecmakelib/lib/CMakeLists.txt
SET(LIBHELLO_SRC hello.cpp)
ADD_LIBRARY(hello SHARED ${LIBHELLO_SRC})
INSTALL(TARGETS hello hello LIBRARY DESTINATION lib)
# INSTALL(FILES hello.h)
/home/ubuntu/cppproject/codecmake/codecmakesrc/CMakeLists.txt
PROJECT(NEWHELLO)
ADD_SUBDIRECTORY(src)
/home/ubuntu/cppproject/codecmake/codecmakesrc/src/CMakeLists.txt
link_libraries(/home/ubuntu/cppproject/codecmakelib/lib)
find_package(hello)
ADD_EXECUTABLE(main main.cpp)
INCLUDE_DIRECTORIES(/home/ubuntu/cppproject/codecmakelib/lib)
TARGET_LINK_LIBRARIES(main hello::hello)