创建源文件main.c,内容如下:
//main.c
#include
int main()
{printf("Hello World!\n");return 0;
创建CMakeLists.txt,内容如下:
//CMakeLists.txt
project(main)
add_executable(main main.c)
创建build文件夹,进入文件夹,执行cmake ..
指令,再执行make指令,即可生成目标文件
创建hello.c文件,内容如下:
//hello.c
#include
void hello(){printf("hello world!\n");
}
创建头文件hello.h,内容如下:
//hello.h
#ifndef __HELLO_H__
#define __HELLO_H__
void hello();
#endif
创建源文件main.c:
//main.c
#include "hello.h"
#include int main(){hello();return 0;
}
创建CMakeLists.txt:
project(main)
set(src_files main.c hello.c)
add_executable(main ${src_files})
创建build文件夹,进入文件夹,执行cmake ..
指令,再执行make指令,即可生成目标文件
在第2步的基础上,把CMakeLists.txt的内容改成如下,生成静态库:
//CMakeLists.txt
project(main)
add_library(hello hello.c)
add_executable(main main.c)
target_link_libraries(main hello)
注意:add_library默认生成的静态库,可以显式指定生成静态库还是动态库:
add_library(hello SHARED hello.c) #生成动态库文件
add_library(hello STATIC hello.c) #生成静态库文件
创建src文件夹,存放main.c,同时在src下面添加CMakeLists.txt:
// ./src/CMakeLists.txt
include_directories(${PROJECT_SOURCE_DIR}/hello)
add_executable(main main.c)
target_link_libraries(main hello)
创建hello文件夹,存放hello.c,hello.h,同时在hello下面添加CMakeLists.txt:
// ./hello/CMakeLists.txt
add_library(hello hello.c)
在最外层创建CMakeLists.txt
// ./CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(main)
add_subdirectory(src)
add_subdirectory(hello)