CMakeList_3

hello.cpp

#include <iostream>
#include "hello.h"

#ifdef USE_ADD
#include "libtest.h"
#endif

int main(int argc, char** argv)
{
#ifdef USE_ADD
  std::cout << add(1, 2) << std::endl;
#endif
  return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)

#直接使用project定义target或者指定下版本,再通过config_file设定版本宏配置自动写入指定头文件
#project(helloworld)
project(helloworld VERSION 1.0)

#option放在configure_file前面否则默认值不生效
option(USE_ADD "Use ADD provided math implementation" ON)

#cmake执行时将hello.h.in中定义的@${target}_VERSION_MAJOR@和@${target}_VERSION_MINOR@替换为VERSION的1和0
#并重新重定向到${PROJECT_BINARY_DIR}下的新文件hello.h
configure_file(hello.h.in hello.h)

#指定CXX的版本
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED True)

#可选宏需要通过配置文件hello.h.in导入
#配置文件额外添加 #cmakedefine USE_ADD 从CMake导入到hello.h,在工程中可以使用
if(USE_ADD)
    add_subdirectory(lib)
    list(APPEND EXTRA_LIBS add)
    list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/lib")
endif()


add_executable(helloworld hello.cpp)

#放在add_executable后面,否则找不到target
#${PROJECT_BINARY_DIR}为CMake的环境变量
target_include_directories(helloworld PUBLIC
                           "${PROJECT_BINARY_DIR}"
                           ${EXTRA_INCLUDES}
                           )
target_link_libraries(helloworld PUBLIC ${EXTRA_LIBS})

hello.h.in

#define HELLO_VERSION_MAJOR @helloworld_VERSION_MAJOR@
#define HELLO_VERSION_MINOR @helloworld_VERSION_MINOR@

liblibtest.h

int add(int a, int b);

liblibtest.cpp

#include "libtest.h"
int add(int a, int b)
{
	return a+b;
}

libCMakeLists.txt

cmake_minimum_required(VERSION 3.10)

project(helloworld VERSION 1.0)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED True)

add_library(add libtest.cpp)

target_include_directories(add PUBLIC
                           "."
                           )
原文地址:https://www.cnblogs.com/kuikuitage/p/14387408.html