1# Minimum CMake required 2cmake_minimum_required(VERSION 2.8.12) 3 4# Project 5project(protobuf-examples) 6 7# Find required protobuf package 8find_package(protobuf CONFIG REQUIRED) 9 10if(protobuf_VERBOSE) 11 message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}") 12endif() 13 14set(CMAKE_INCLUDE_CURRENT_DIR TRUE) 15 16# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F 17if(MSVC AND protobuf_MSVC_STATIC_RUNTIME) 18 foreach(flag_var 19 CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE 20 CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) 21 if(${flag_var} MATCHES "/MD") 22 string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") 23 endif(${flag_var} MATCHES "/MD") 24 endforeach() 25endif() 26 27foreach(example add_person list_people) 28 set(${example}_SRCS ${example}.cc) 29 set(${example}_PROTOS addressbook.proto) 30 31 #Code Generation 32 if(protobuf_MODULE_COMPATIBLE) #Legacy Support 33 protobuf_generate_cpp(${example}_PROTO_SRCS ${example}_PROTO_HDRS ${${example}_PROTOS}) 34 list(APPEND ${example}_SRCS ${${example}_PROTO_SRCS} ${${example}_PROTO_HDRS}) 35 else() 36 37 foreach(proto_file ${${example}_PROTOS}) 38 get_filename_component(proto_file_abs ${proto_file} ABSOLUTE) 39 get_filename_component(basename ${proto_file} NAME_WE) 40 set(generated_files ${basename}.pb.cc ${basename}.pb.h) 41 list(APPEND ${example}_SRCS ${generated_files}) 42 43 add_custom_command( 44 OUTPUT ${generated_files} 45 COMMAND protobuf::protoc 46 ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${proto_file_abs} 47 COMMENT "Generating ${generated_files} from ${proto_file}" 48 VERBATIM 49 ) 50 endforeach() 51 endif() 52 53 #Executable setup 54 set(executable_name ${example}_cpp) 55 add_executable(${executable_name} ${${example}_SRCS} ${${example}_PROTOS}) 56 if(protobuf_MODULE_COMPATIBLE) #Legacy mode 57 target_include_directories(${executable_name} PUBLIC ${PROTOBUF_INCLUDE_DIRS}) 58 target_link_libraries(${executable_name} ${PROTOBUF_LIBRARIES}) 59 else() 60 target_link_libraries(${executable_name} protobuf::libprotobuf) 61 endif() 62 63endforeach() 64