cmake使用
nix-shell -p cmake
配置
CMakeLists.txt
到项目根目录
cmake_minimum_required(VERSION 3.1)
project(demo)
include_directories(.)
# 构建可执行文件
add_executable(${PROJECT_NAME} main.c)
Hello, World,
main.c
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
编译,生成可执行文件
# 创建build目录,在build里面编译
mkdir build
cd build
cmake ..
make
./demo
file ./demo
静态编译
# 原始操作
gcc -static ../main.c -o main
# camake操作
cmake -DBUILD_SHARED_LIBS=OFF ..
# 或者配置, 似乎交叉编译本身就是静态的
set(BUILD_SHARED_LIBS OFF)
配置交叉编译,增加工具链配置
# 定义的配置都应该在project()方法之前
cmake_minimum_required(VERSION 3.1)
# 交叉编译
# export CC=/home/jcleng/desktop/work/mipseltools-gcc412-lnx26-master/bin/mipsel-linux-gcc
# export CXX=/home/jcleng/desktop/work/mipseltools-gcc412-lnx26-master/bin/mipsel-linux-g++
# 设置目标系统
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR mips)
set(CMAKE_C_FLAGS "-std=c99")
# 设置工具链目录
set(TOOL_CHAIN_DIR /home/jcleng/desktop/work/mipseltools-gcc412-lnx26-master)
set(TOOL_CHAIN_INCLUDE ${TOOL_CHAIN_DIR}/include ${TOOL_CHAIN_DIR}/mipsel-linux/include)
set(TOOL_CHAIN_LIB ${TOOL_CHAIN_DIR}/lib ${TOOL_CHAIN_DIR}/mipsel-linux/lib)
# 设置编译器位置
set(CMAKE_C_COMPILER "${TOOL_CHAIN_DIR}/bin/mipsel-linux-gcc")
set(CMAKE_CXX_COMPILER "${TOOL_CHAIN_DIR}/bin/mipsel-linux-g++")
# 设置Cmake查找主路径
set(CMAKE_FIND_ROOT_PATH ${TOOL_CHAIN_DIR}/mipsel-linux)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
# 只在指定目录下查找库文件
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
# 只在指定目录下查找头文件
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# 只在指定目录下查找依赖包
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
include_directories(${TOOL_CHAIN_DIR}/include ${TOOL_CHAIN_DIR}/mipsel-linux/include)
set(CMAKE_INCLUDE_PATH ${TOOL_CHAIN_INCLUDE})
set(CMAKE_LIBRARY_PATH ${TOOL_CHAIN_LIB})
set(BUILD_SHARED_LIBS OFF)
project(demo)
include_directories(.)
# 构建可执行文件
add_executable(${PROJECT_NAME} main.c)