main.cide
#include<stdio.h> int main(void){ printf("hello world\n"); return 0; }
CMakeLists.txtui
# 指定最小版本 cmake_minimum_required (VERSION 3.3) # 指定工程名和語言類型 project (hello C) # debug set(CMAKE_BUILD_TYPE "Debug") # c99 set(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]# make Scanning 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
# 指定最小版本 cmake_minimum_required (VERSION 3.3) # 指定工程名和語言類型 project (hello C) # debug set(CMAKE_BUILD_TYPE "Debug") # c99 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -g") # 添加子目錄 add_subdirectory(src)
# 頭文件目錄 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 <stdio.h> #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_H int 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]# make Scanning 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 = 3 Hello, World! [root@cstudy build]#