决定代码的组织方式及其编译方式,也是程序设计的一部分。因此,我们需要cmake和autotools这样的工具来帮助我们构建并维护项目代码。cmake和autotools正是makefile的上层工具,它们的目的正是为了产生可移植的makefile,并简化自己动手写makefile时的巨大工作量。
下载 cmake
http://www.cmake.org/cmake/resources/software.html
#tar -xvf cmake-3.22.0-rc2.tar.gz
#cd cmake-3.22.0-rc2
#./bootstrap
#make
#make install
cmake 会默认安装在 /usr/local/bin 下面
建立工程
q@ubuntu:~/test_cmake_prj$ tree .
.
├── build
├── CMakeLists.txt
├── main.c
└── src
├── CMakeLists.txt
├── test.c
└── test.h
2 directories, 5 files
q@ubuntu:~/test_cmake_prj$ cat CMakeLists.txt
PROJECT(MAIN_prj) # 项目名称
CMAKE_MINIMUM_REQUIRED(VERSION 2.6) # cmake最低版本需求,不加入此行会受到警告信息
ADD_SUBDIRECTORY(src) # 指明本项目包含一个子目录src, 进入目录src对其中的CMakeLists.txt进行解析
AUX_SOURCE_DIRECTORY(. DIR_SRCS) # 把当前目录(.)下所有源代码文件和头文件加入变量DIR_SRCS
ADD_EXECUTABLE(main ${DIR_SRCS})
# 生成应用程序 main
TARGET_LINK_LIBRARIES(main Test) # 指明可执行文件 main 需要连接一个名为Test的链接库
q@ubuntu:~/test_cmake_prj$ cat main.c
#include<stdio.h>
int main(void)
{
char s[] = "Hello,World\n";
printf(s);
println(s);
return 0;
}
q@ubuntu:~/test_cmake_prj$ cat src/CMakeLists.txt
AUX_SOURCE_DIRECTORY(. DIR_TEST1_SRCS) # 把当前目录(.)下所有源代码文件和头文件加入变量DIR_TEST1_SRCS
ADD_LIBRARY(Test ${DIR_TEST1_SRCS}) # 将src目录中的源文件编译为共享库
q@ubuntu:~/test_cmake_prj$ cat src/test.c
#include <stdio.h>
#include "test.h"
void println()
{
printf("PI=%.2f\n", PI);
}
q@ubuntu:~/test_cmake_prj$ cat src/test.h
#define PI 3.14
void println();
生成 Makefile - cmake
注意事项,尽量在新建的 build
目录中进行生成操作,注意最后参数 ..
为上级目录。
q@ubuntu:~/test_cmake_prj/build$ sudo ../../cmake-3.22.2-linux-x86_64/bin/cmake ..
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Deprecation Warning at CMakeLists.txt:2 (CMAKE_MINIMUM_REQUIRED):
Compatibility with CMake < 2.8.12 will be removed from a future version of
CMake.
Update the VERSION argument <min> value or use a ...<max> suffix to tell
CMake that the project does not need compatibility with older versions.
-- Configuring done
-- Generating done
-- Build files have been written to: /home/q/test_cmake_prj/build
生成位置如下:
q@ubuntu:~/test_cmake_prj/build$ ls
CMakeCache.txt CMakeFiles cmake_install.cmake Makefile src