CMake系列(二) CMake简单的例子

CMake系列(二) CMake简单的例子



1. Hello World

目录结构

└── 01-hello-cmake
├── CMakeLists.txt
└── main.c

源文件

main.c

#include <stdio.h>

int main(int argc, char *argv[])
{
   printf("main: cmake\r\n");
   return 0;
}

CMakeLists.txt

# Set the minimum version of CMake that can be used
# To find the cmake version run
# $ cmake --version
cmake_minimum_required(VERSION 3.5)

# Set the project name
project(hello_cmake)

# Add an executable
add_executable(hello_cmake main.c)

第一行用于指定cmake最低版本
第二行指定项目名称(这个名称是任意的)
第三行指定编译一个可执行文件,hello_cmake 是第一个参数,表示生成可执行文件的文件名(这个文件名也是任意的),第二个参数main.c则用于指定源文件。

编译

	$  mkdir build
	$  cd build/
	$  cmake ..
	$  make

测试

	$  ./hello_cmake
	main:cmake

2. 多个源且包含头文件

目录结构

├── CMakeLists.txt
├── include
│ └── Hello.h
└── src
├── Hello.c
└── main.c

源文件

main.c

#include "Hello.h"

int main(int argc, char *argv[])
{
    Hello_print();
    return 0;
}

Hello.c

#include "Hello.h"

void Hello_print(void)
{
    printf("hello: cmake\r\n");
}

头文件

Hello.h

#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>

void Hello_print(void);

#endif

CMakeLists.txt

# Set the minimum version of CMake that can be used
# To find the cmake version run
# $ cmake --version
cmake_minimum_required(VERSION 3.5)

# Set the project name
project(hello_headers)

# Create a sources variable with a link to all cpp files to compile
set(SOURCES
    src/Hello.c
    src/main.c
)

# Add an executable with the above sources
add_executable(hello_headers ${SOURCES})

# Set the directories that should be included in the build command for this target
# when running g++ these will be included as -I/directory/path/
target_include_directories(hello_headers
    PRIVATE 
        ${PROJECT_SOURCE_DIR}/include
)

第三行创建一个SOURCES变量,其中包含一个指向要编译的所有c文件的链接。
第五行添加头文件目录。

注意

include_directories()和target_include_directories()的区别。

编译

	$  mkdir build
	$  cd build/
	$  cmake ..
	$  make

测试

	$  ./hello_cmake
	hello: cmake
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胖茄子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值