菜鸟笔记
提升您的技术认知

CMake 简单的例子

阅读 : 1486

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