├── CMakeLists.txt
├── include
│ └── Static.h
└── src
├── Static.c
└── main.c
main.c
#include "Static.h"
int main(int argc, char *argv[])
{
Static_print();
return 0;
}
Static.c
#include "Static.h"
void Static_print(void)
{
printf("static hello: cmake\r\n");
}
Hello.h
#ifndef __STATIC_H__
#define __STATIC_H__
#include
void Static_print(void);
#endif
cmake_minimum_required(VERSION 3.5)
project(static_library)
############################################################
# Create a library
############################################################
#Generate the static library from the library sources
add_library(static_library STATIC
src/Static.c
)
target_include_directories(static_library
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
############################################################
# Create an executable
############################################################
# Add an executable with the above sources
add_executable(hello_binary
src/main.c
)
# link the new static_library target with the hello_binary target
target_link_libraries( hello_binary
PRIVATE
static_library
)
第三行add_library 创建一个static_library的静态库,源文件为Hello.c
第六行当需要使用static_library静态库创建可执行文件时,需要使用target_link_libraries添加库文件。
$ mkdir build
$ cd build/
$ cmake ..
$ make
build目录下会出现libstatic_library.a文件
$ ./hello_cmake
static hello: cmake
├── 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("shared hello: cmake\r\n");
}
Hello.h
#ifndef __HELLO_H__
#define __HELLO_H__
#include
void Hello_print(void);
#endif
cmake_minimum_required(VERSION 3.5)
project(hello_library)
############################################################
# Create a library
############################################################
#Generate the shared library from the library sources
add_library(hello_library SHARED
src/Hello.c
)
add_library(hello::library ALIAS hello_library)
target_include_directories(hello_library
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
############################################################
# Create an executable
############################################################
# Add an executable with the above sources
add_executable(hello_binary
src/main.c
)
# link the new hello_library target with the hello_binary target
target_link_libraries( hello_binary
PRIVATE
hello::library
)
第三行add_library 创建一个hello_library的动态库,源文件为Hello.c
第四行add_library 创建一个别名库hello::library,就是给hello_library换个名字,名字叫hello::library
第六行当需要使用hello_library静态库创建可执行文件时,需要使用target_link_libraries添加库文件。
$ mkdir build
$ cd build/
$ cmake ..
$ make
build目录下会出现libhello_library.so文件
$ ./hello_cmake
static hello: cmake