我们考虑这样一种场景:
现有目录结构如下:
|-cmakeTest
|-shell.sh
|-CMakeLists.txt
|-src
|-main.c
我们需要把 src/main.c 提取到 cmakeTest 目录下,对其进行编译。我们的做法是这样子的:shell.sh 脚本执行复制文件操作,CMakeLists.txt 调用 shell.sh 获得 main.c 并完成构建。
main.c 是这样的:
#include <stdio.h>
int main()
{
printf("Hello CMake!\n");
return 0;
}
shell.sh 是这样的:
echo "Begin"
cp ../$1/main.c ../main.c
echo "End"
注意 cp 语句中,main.c 的路径写法,还有$1
参数。一会儿解释为什么是这样的。
重点来了,CMakeLists.txt 是这样的:
cmake_minimum_required (VERSION 2.6)
execute_process(COMMAND sh ../shell.sh src)
aux_source_directory(. SRC_LIST)
add_executable(main ${SRC_LIST})
CMakeLists.txt 通过 execute_process() 命令调用了 shell.sh 并传入了参数 src 。这里的 src 就是 shell.sh 里面 cp 语句的$1
,cp 语句展开后就是:
cp ../src/main.c ../main.c
至于这奇怪的 ../
路径,是因为 execute_process() 命令开起了一个子线程来执行 shell 命令,这个子线程的工作目录和当前工作目录一致。我会采用外部构建方式执行 CMake,也就是新建 build 目录,进入 build 目录执行 CMake,于是子线程的工作目录也就是当前工作目录—— build,所以需要../
才能够正确找到需要的文件。
完整的演示如下:
$ mkdir build
$ cd build
$ cmake ..
-- The C compiler identification is GNU 4.8.4
-- The CXX compiler identification is GNU 4.8.4
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
Begin
End
-- Configuring done
-- Generating done
-- Build files have been written to: /????/CMakeTest/build
$ make
Scanning dependencies of target main
[100%] Building C object CMakeFiles/main.dir/main.c.o
Linking C executable main
[100%] Built target main
$ ./main
Hello CMake!