hello world
代码
main.c
#includeint main(void){ printf("hello world\n"); return 0;}
CMakeLists.txt
# 指定最小版本cmake_minimum_required (VERSION 3.3)# 指定工程名和语言类型project (hello C)# debugset(CMAKE_BUILD_TYPE "Debug")# c99set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -g")# 指定源码列表aux_source_directory(. SRCS)# 指定可执行程序add_executable(hello ${SRCS})
运行
[root@cstudy hello]# mkdir build[root@cstudy hello]# cd build/[root@cstudy build]# cmake ..-- The C compiler identification is GNU 4.8.5-- Check for working C compiler: /usr/bin/cc-- Check for working C compiler: /usr/bin/cc -- works-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Detecting C compile features-- Detecting C compile features - done-- Configuring done-- Generating done-- Build files have been written to: /root/code/cmake/hello/build[root@cstudy build]# makeScanning dependencies of target hello[ 50%] Building C object CMakeFiles/hello.dir/main.c.o[100%] Linking C executable hello[100%] Built target hello[root@cstudy build]# ./hello hello world[root@cstudy build]#
添加子目录
目录结构
├── CMakeLists.txt├── include│ └── util.h└── src ├── CMakeLists.txt ├── main.c └── util.c
顶层 CMakeLists.txt
# 指定最小版本cmake_minimum_required (VERSION 3.3)# 指定工程名和语言类型project (hello C)# debugset(CMAKE_BUILD_TYPE "Debug")# c99set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -g")# 添加子目录add_subdirectory(src)
子目录 CMakeLists.txt
# 头文件目录include_directories(${PROJECT_SOURCE_DIR}/include)# 源文件列表aux_source_directory(. SRCS)# 可执行文件目录set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)# 可执行文件add_executable(hello ${SRCS})
代码
[root@cstudy hello]# # main.c[root@cstudy hello]# cat src/main.c #include#include "../include/util.h"int main() { int a = 1; int b = 2; printf("%d + %d = %d\n",a,b,sum(a,b)); printf("Hello, World!\n"); return 0;}[root@cstudy hello]# # util.h[root@cstudy hello]# cat include/util.h #ifndef HELLO_UTIL_H#define HELLO_UTIL_Hint sum(int a, int b );#endif //HELLO_UTIL_H[root@cstudy hello]# # util.c[root@cstudy hello]# cat src/util.c #include "../include/util.h"int sum(int a, int b ){ return a + b;}[root@cstudy hello]#
运行
[root@cstudy hello]# mkdir build[root@cstudy hello]# cd build[root@cstudy build]# cmake ..-- The C compiler identification is GNU 4.8.5-- Check for working C compiler: /usr/bin/cc-- Check for working C compiler: /usr/bin/cc -- works-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Detecting C compile features-- Detecting C compile features - done-- Configuring done-- Generating done-- Build files have been written to: /root/code/cmake/hello/build[root@cstudy build]# makeScanning dependencies of target hello[ 33%] Building C object src/CMakeFiles/hello.dir/util.c.o[ 66%] Building C object src/CMakeFiles/hello.dir/main.c.o[100%] Linking C executable ../bin/hello[100%] Built target hello[root@cstudy build]# ./bin/hello 1 + 2 = 3Hello, World![root@cstudy build]#