创建库
在mymath 目录下的CMakeLists.txt里增加如下内容
#mymath 目录下有CMakeLists.txt ,mymath.c mymath.h
mytest/mymath/CMakeLists.txt:
#生成mymath 库,默认是生成静态库
add_library(mymath mymath.c)
#发布 ${PROJECT_SOURCE_DIR}/mymath"这个路径下的头文件到工程里面,整个工程里的.c 里
#里这样调用#include “mymath.h”
target_include_directories(mymath PUBLIC "${PROJECT_SOURCE_DIR}/mymath" )
在mytest 目录下的CMakeLists.txt 里添加如下内容
mytest/CMakeLists.txt:
add_subdirectory(mymath)
target_link_libraries(mytest PUBLIC mymath)
#发布 ${PROJECT_BINARY_DIR}这个路径下的头文件到工程里面,整个工程里的.c 里
#里这样调用#include “xxx.h”,一般这个下边的头文件都是动态生成的,比如用configure_file
target_include_directories(mytest PUBLIC "${PROJECT_BINARY_DIR}" )
添加选项
在mymath 目录下的CMakeLists.txt里增加如下内容
option(USE_MYMATH "Use tutorial provided math implementation" ON) if (USE_MYMATH) target_compile_definitions(mymath PRIVATE "USE_MYMATH") add_library(mysqrt STATIC mysqrt.c ) target_link_libraries(mymath PRIVATE mysqrt) endif()
在mymath.c 中code
#ifdef USE_MYMATH
# include "mysqrt.h"
#else
# include "math.h"
#endif
...
#ifdef USE_MYMATH
return mysqrt(x);
#ese
return sqrt(x);
#endif
...