由于之前编译代码一直用Makefile, 但是新公司都用CMake来编译,就花了一天的时间把Makefile换成CMakeLists.txt. 把学习的过程记录下来
先介绍下代码目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| . ├── CMakeLists.txt ├── include │ ├── event.h │ ├── openssl ├── lib │ ├── libevent.a │ └── libssl.a ├── server │ ├── CMakeLists.txt │ ├── server.cpp │ ├── server.h │ ├── licAuth.conf ├── src │ ├── CMakeLists.txt │ ├── src1.cpp │ ├── src1.h └── test ├── CMakeLists.txt ├── test1.cpp └── test2.cpp
|
- include: 头文件, gcc/g++的 -I后面跟的就是此目录
- lib: 静态库, -L 选项后面跟的目录
- server: server程序,这个程序要调用src目录下的所有代码产生的静态库, 下面有个licAuth.conf是默认的配置文件,make install的时候要安装到/etc/目录下面
- src: 源文件, 要封装成静态库以供别人调用
- test: 一些测试程序,测试src目录在的代码
开始
在我们写的代码目录src, server, test下都新建一个CMakeLIsts.txt, 根目录下也要有, 注意不要拼错了,Lists大写的后面跟s.
根目录下./CMakeLists.txt
1 2 3 4 5
| cmake_minimum_required (VERSION 2.8) project(licAuth) add_subdirectory(src) add_subdirectory(server) add_subdirectory(test)
|
src目录./src/CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11
| cmake_minimum_required(VERSION 2.8) project(lib)
include_directories(${licAuth_SOURCE_DIR}/include) link_directories(${licAuth_SOURCE_DIR}/lib)
add_compile_options(-Wall -std=c++11 -Wunused-variable)
aux_source_directory(. DIR_LIB_SRCS) add_library (lic ${DIR_LIB_SRCS})
|
server目录 ./server/CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| cmake_minimum_required (VERSION 2.8) project (server)
include_directories(${licAuth_SOURCE_DIR}/include ${lib_SOURCE_DIR})
link_directories(${licAuth_SOURCE_DIR}/lib ${lib_SOURCE_DIR})
add_compile_options(-Wall -std=c++11 -O3 -flto -Wl,--no-as-needed -Wunused-variable)
add_executable(server server.cpp)
target_link_libraries(server lic ssl crypto pthread protobuf event machineid)
add_executable(client client.cpp) target_link_libraries(client lic ssl crypto pthread protobuf event machineid)
INSTALL(FILES licAuth.conf DESTINATION /etc/)
|
test目录下的就跟server目录差不多了
编译
编译的时候最好新建一个目录,在新建的目录在cmake, 这样可以很干净的删除cmake的中间产物,比如
1 2 3 4
| mkdir build cd build cmake .. make
|
当测试完毕的时候 直接把build目录删除就好了 或者cmake出错的时候,也能清空build目录重来.