CMake语法笔记(1)
cmake_minimum_required(VERSION3.4)
project(hello_cmake)
add_executable(hello_cmake main.cpp)
set(sources src/Hello.cpp src/main.cpp)多个源文件可用此方法。
add_executable(${PROJECT_NAME}${SOURCES})
target_include_directories(hello_headers PRIVATE ${PROJECT_SOURCE_DIR}/include) same as -I/directory/path
add_library(hello_library STATIC src/hello.cpp)生成静态库
target_include_directories(hello_library PUBLIC ${PROJECT_SOURCE_DIR}/include)用pubilc因为不只创建库的时候要用到,创建生成文件还要链接到库。
target_link_libraries(hello_binary PRIVATE hello_library)
add_library(hello_library SHARED src/hello.cpp) 生成动态库
add_library(hell0::library ALIAS hello_library) 给库创建别名
install (指令顺序cmake-make-sudo make install)(先构建,再加下列指令)
install(TARGETS cmake_example_inst_bin DESTINATION bin)
install(TARGETS cmake_example_inst LIBRARY DESTINATION lib)
install(DIRECTORY ${DIRECTORY_SOURCE_DIR}/include/ DESTINATION include)
install(FILES cmake-examples.conf DESTINATION etc)
添加默认build type
cmake .. -DCMAKE_BUILD_TYPE=Release
-
Release
-O3 -DNDEBUG -
Debug
-g -
MinSizeRel
-Os -DNDEBUG -
RelWithDebInfo
-O2 -g -DNDEBUG
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message("Setting build type to 'RelWithDebInfo' as none was specified.") set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif()
带-flag编译
target_compile_definitions(cmake_examples_compile_flags
PRIVATE EX3
)
Find package 第三方库
find_package()会去/usr/share/cmake/Modules找FindXXX.cmake文件。
A basic example of finding boost is below:
find_package(Boost 1.46.1 REQUIRED COMPONENTS filesystem system)
The arguments are:
-
Boost - Name of the library. This is part of used to find the module file FindBoost.cmake
-
1.46.1 - The minimum version of boost to find
-
REQUIRED - Tells the module that this is required and to fail it it cannot be found
-
COMPONENTS - The list of libraries to find.
对于Alies/Imported targets
target_link_libraries( third_party_include
PRIVATE
Boost::filesystem
)
对于Non-Alies targets
# Include the boost headers
target_include_directories( third_party_include
PRIVATE ${Boost_INCLUDE_DIRS}
)
# link against the boost libraries
target_link_libraries( third_party_include
PRIVATE
${Boost_SYSTEM_LIBRARY}
${Boost_FILESYSTEM_LIBRARY}
)
cmake .. -DCMAKE_C_COMPILER=clang-3.6 -DCMAKE_CXX_COMPILER=clang++-3.6 通过在cmake时加-flag更换编译器或连接器
-
CMAKE_C_COMPILER - The program used to compile c code.
-
CMAKE_CXX_COMPILER - The program used to compile c++ code.
-
CMAKE_LINKER - The program used to link your binary.
cmake .. -G Ninja 生成别的生成器可用的生成文件,如Ninja。可用cmake -help最后查看支持的生成器。
set (CMAKE_CXX_STANDARD 11) 设置成c++11标准
target_compile_features(hello_cpp11 PUBLIC cxx_auto_type) 或增加特定特征如auto类型
浙公网安备 33010602011771号