target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
)
把配置文件写到二进制树中。
# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
上面的命令指定C++的标准。
Step 2:增加一个库
把自定义的库文件放到子目录:MathFunctions;库包含头文件:MathFunctions.h和源文件:mysqrt.cxx;有一个方法是mysqrt。
add_library(MathFunctions mysqrt.cxx)的cmakeLists.txt到MathFunctions的子目录中。
为了使用mathFunctions的功能,高一级的cmakeLists的写法如下:
# add the MathFunctions library
add_subdirectory(MathFunctions)
# add the executable
add_executable(Tutorial tutorial.cxx)
target_link_libraries(Tutorial PUBLIC MathFunctions)
# 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}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)
为了让这个math库变为可配置的。
option(USE_MYMATH "Use tutorial provided math implementation" ON)
# configure a header file to pass some of the CMake settings
# to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
改变上一级的cmakelist.txt:
if(USE_MYMATH)
add_subdirectory(MathFunctions)
list(APPEND EXTRA_LIBS MathFunctions)
list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()
# add the executable
add_executable(Tutorial tutorial.cxx)
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}
)
在 in tutorial.cxx中使用宏定义:
#ifdef USE_MYMATH
# include "MathFunctions.h"
#endif
#ifdef USE_MYMATH
const double outputValue = mysqrt(inputValue);
#else
const double outputValue = sqrt(inputValue);
#endif
编译:
cmake ../Step2 -DUSE_MYMATH=OFF
Step 3:添加库的使用要求
1)接口的使用,是用户需要的,需要修改MathFunctions/CMakeLists.txt增加下面一行
:
target_include_directories(MathFunctions INTERFACE ${CMAKE_CURRENT_SOURCE_DIR} )
如果增加了上面一行,那就可以修改上一级的CMakeLists.txt:
if(USE_MYMATH) add_subdirectory(MathFunctions) list(APPEND EXTRA_LIBS MathFunctions) endif()
And here:
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}" )