Chinaunix首页 | 论坛 | 博客
  • 博客访问: 347885
  • 博文数量: 94
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 606
  • 用 户 组: 普通用户
  • 注册时间: 2015-09-30 08:58
个人简介

x

文章分类

全部博文(94)

文章存档

2019年(4)

2018年(10)

2017年(26)

2016年(38)

2015年(16)

我的朋友

分类: C/C++

2017-10-24 10:58:07

#1) 项目工程文件目录结构
    

#2) 源码
##2.1) hello/include/hello.h

点击(此处)折叠或打开

  1. #ifndef HELLOWORLD_HELLO_H
  2. #define HELLOWORLD_HELLO_H

  3. extern void hello(void);

  4. #endif //HELLOWORLD_HELLO_H

##2.2) hello/src/hello.c

点击(此处)折叠或打开

  1. #include "hello.h"
  2. #include <stdio.h>

  3. void hello()
  4. {
  5.     printf("hello.\n");
  6. }

##2.3) hello/CMakeLists.txt

点击(此处)折叠或打开

  1. include_directories(./include)
  2. set(DIR_SRCS ./src/hello.c)
  3. add_library(hello SHARED ${DIR_SRCS})

##2.4) world/include/world.h

点击(此处)折叠或打开

  1. #ifndef HELLOWORLD_WORLD_H
  2. #define HELLOWORLD_WORLD_H

  3. extern void world(void);

  4. #endif //HELLOWORLD_WORLD_H

##2.5) world/src/world.c

点击(此处)折叠或打开

  1. #include "world.h"
  2. #include <stdio.h>

  3. void world()
  4. {
  5.     printf("world.\n");
  6. }

##2.6) world/CMakeLists.txt

点击(此处)折叠或打开

  1. include_directories(./include)
  2. set(DIR_SRCS ./src/world.c)
  3. add_library(world SHARED ${DIR_SRCS})

##2.7) app/main.c

点击(此处)折叠或打开

  1. #include "hello.h"
  2. #include "world.h"

  3. int main()
  4. {
  5.     hello();
  6.     world();

  7.     return 0;
  8. }

##2.8) CMakeLists.txt

点击(此处)折叠或打开

  1. cmake_minimum_required(VERSION 3.5)
  2. project(HelloWorld)
  3. set(CMAKE_C_STANDARD 99)
  4. include_directories(hello/include world/include)
  5. set(DIR_SRCS ./app/main.c)
  6. add_subdirectory(hello)
  7. add_subdirectory(world)
  8. add_executable(HelloWorld ${DIR_SRCS})
  9. target_link_libraries(HelloWorld hello world)

#3) 配置
由于顶层目录下CMakeLists.txt包含子目录下的CMakeLists.txt文件,所以只需在顶层目录下运行“cmake .”命令即可。
但“cmake .”执行完毕后,会在工程顶层目录下生成大量cmake输出的临时文件。

我们可以在顶层目录下单独创建一个空目录,专门由于存储cmake配置、make编译输出的文件。使用命令如下:

点击(此处)折叠或打开

  1. # cd cmake-build-debug
  2. # cmake ..

  3. # ls
  4. CMakeCache.txt  CMakeFiles  cmake_install.cmake  hello  Makefile  world

  5. # ls hello/
  6. CMakeFiles  cmake_install.cmake  Makefile

  7. # ls world/
  8. CMakeFiles  cmake_install.cmake  Makefile
此时可以看到cmake-build-debug存放很多cmake输出文件,包括工程顶层目录对应的Makefile文件,还有工程子目录下对应的Makefile文件。

#4) 编译
在上面通过cmake输出整个工程编译的Makefile,只需在工程顶层目录下使用命令

点击(此处)折叠或打开

  1. # make -C cmake-build-debug

#5) 总结
通过上面使用cmake去配置整个项目编译规则,明显感觉比直接去写Makefile要简单很多,而且从工程配置到编译的过程中,整个工程源码目录下不会有其它文件产生,这种做法感觉很优雅,所有的cmake输出文件(包含Makefile),make输出文件(包括*.o/*.a/*.so)都在cmake-build-debug目录下,如果下次想从新配置、编译,只需删除此目录下所有文件和子目录。

最后附上源码:HelloWorld.zip

阅读(4731) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~