文章目录
1. 自定义库
添加一个新的文件夹 mathfunctions存放我们自定义的库文件, 这个文件夹里面新建三个文件:mysqrt.cxx(自定义库内容的实现),.h文件对库的借口声明等,CMakelists.txt说明本文件下定义了库文件。
其中CMakelists.txt中的内容为:
2. 引用自定义库
在顶层的CMakeLists.txt中添加下面的语句,
2.1 添加头文件目录
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h "MathFunctions.h"
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)
2.2 设置要链接的库文件的名称
可以链接一个,也可以多个,中间使用空格分隔.
target_link_libraries(Tutorial PUBLIC MathFunctions)
# 以下写法都可以:
target_link_libraries(myProject comm) # 连接libhello.so库,默认优先链接动态库
target_link_libraries(myProject libcomm.a) # 显示指定链接静态库
target_link_libraries(myProject libcomm.so) # 显示指定链接动态库
target_link_libraries(myProject libcomm.so) #这些库名写法都可以。
target_link_libraries(myProject comm)
target_link_libraries(myProject -lcomm)
2.3 添加外部项目文件夹
一般情况下,我们的项目各个子项目都在一个总的项目根目录下,但有的时候,我们需要使用外部的文件夹,怎么办呢?
add_subdirectory命令,可以将指定的文件夹加到build任务列表中。
# add the MathFunctions library
add_subdirectory(MathFunctions)
3. 设置选项定义是否使用自定义库
3.1 CMakeLists.txt
在顶层的CMakeLists.txt中添加选项
# a default value of ON that can be changed by the user.
option(USE_MYMATH "Use tutorial provided math implementation" ON)
然后我们就可以在顶层的CMakeLists.txt 中,添加下面的选项以决定是否包含自定义的库函数:
if(USE_MYMATH)
add_subdirectory(MathFunctions)
list(APPEND EXTRA_LIBS MathFunctions)
list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()
target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
${EXTRA_INCLUDES}
)
Note :
the use of the variable EXTRA_LIBS to collect up any optional libraries to later be linked into the executable. The variable EXTRA_INCLUDES is used similarly for optional header files.
3.2 TutorialConfig.h.in
然后在我们想要在cxx代码中就可以根据CMakeLists中设置的option来决定是否使用自定义的函数,我们需要在confiration文件TutorialConfig.h.in中添加下面的语句,
#cmakedefine USE_MYMATH
3.3 cxx
然后我们就可以在cxx文件中使用这个参数:
例如:
#ifdef USE_MYMATH
# include "MathFunctions.h"
#endif
#ifdef USE_MYMATH
const double outputValue = mysqrt(inputValue);
#else
const double outputValue = sqrt(inputValue);
#endif