CMake - 跨平台编译脚本写法(Windows/Linux/Android/MacOS/iOS)

简介

认识CMake

  • CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。
  • 能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的automake。
  • CMake 的组态档取名为 CMakeLists.txt。

安装

下载cmake地址 https://cmake.org/download/

Windows版本

  安装直接运行EXE

LINUX/MAC版本

  cmake-..*tar.gz为下载下来的源码包

  tar xvf cmake-..*.tar.gz

  cd cmake-..*

  ./bootstrap

  make

  make install

应用

构建工程目录

编写程序源码

hello.h

#if !defined(__GNUC__) && defined(TEST_EXPORTS)
#define TEST_API __declspec(dllexport)
#elif !defined(__GNUC__) && !defined(TEST_IMPORTS_IGNORE)
#define TEST_API __declspec(dllimport)
#else
#define TEST_API 
#endif
​
TEST_API void print_hello_world(void);

hello.c

#include 
​
void print_hello_world(void)
{
    printf("hello world!\n");
}

main.c

#include "hello.h"int main()
{
    print_hello_world();
    return 0;
}

编写编译脚本

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)
​
set(PROJECT_NAME mytest)
set(LIB_NAME hello)
​
#####   设置编译32位工程   #####
​
IF (APPLE)         ## mac/ios平台编译64位库     
set(USE_32BITS 0)
ELSE()
set(USE_32BITS 1)
ENDIF()
​
####    设置编译参数    #####
​
if(USE_32BITS)
    message(STATUS "Compiling project using 32 bits")
    set(CMAKE_C_FLAGS   "${CMAKE_C_FLAGS}   -m32")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
endif(USE_32BITS)
​
####    头文件目录    #####
​
include_directories(${PROJECT_SOURCE_DIR}/include)
​
####    windows平台设置dllexport,兼容头文件    #####
​
IF(WIN32)
    add_definitions(-DTEST_EXPORTS)
ENDIF(WIN32)
​
####    编译动态库    #####
​
add_library(${LIB_NAME} SHARED 
    ${PROJECT_SOURCE_DIR}/src/hello.c
)
​
####    编译程序    #####
​
add_executable(${PROJECT_NAME} ${PROJECT_SOURCE_DIR}/src/main.c)
target_link_libraries(${PROJECT_NAME}
        ${LIB_NAME}
)

build.sh

build.sh源码下载地址:https://download.csdn.net/download/qq_40179343/19791239

使用说明

 

posted @ 2022-06-09 21:04  Citrusliu  阅读(1030)  评论(0编辑  收藏  举报