Merge pull request #16122 from alalek:cmake_update_cpu_compiler_detection
[platform/upstream/opencv.git] / cmake / OpenCVFindProtobuf.cmake
1 # If protobuf is found - libprotobuf target is available
2
3 set(HAVE_PROTOBUF FALSE)
4
5 if(NOT WITH_PROTOBUF)
6   return()
7 endif()
8
9 ocv_option(BUILD_PROTOBUF "Force to build libprotobuf from sources" ON)
10 ocv_option(PROTOBUF_UPDATE_FILES "Force rebuilding .proto files (protoc should be available)" OFF)
11
12 function(get_protobuf_version version include)
13   file(STRINGS "${include}/google/protobuf/stubs/common.h" ver REGEX "#define GOOGLE_PROTOBUF_VERSION [0-9]+")
14   string(REGEX MATCHALL "[0-9]+" ver ${ver})
15   math(EXPR major "${ver} / 1000000")
16   math(EXPR minor "${ver} / 1000 % 1000")
17   math(EXPR patch "${ver} % 1000")
18   set(${version} "${major}.${minor}.${patch}" PARENT_SCOPE)
19 endfunction()
20
21 if(BUILD_PROTOBUF)
22   add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/protobuf")
23   set(HAVE_PROTOBUF TRUE)
24 else()
25   unset(Protobuf_VERSION CACHE)
26   find_package(Protobuf QUIET)
27
28   # Backwards compatibility
29   # Define camel case versions of input variables
30   foreach(UPPER
31       PROTOBUF_FOUND
32       PROTOBUF_LIBRARY
33       PROTOBUF_INCLUDE_DIR
34       PROTOBUF_VERSION
35       )
36       if (DEFINED ${UPPER})
37           string(REPLACE "PROTOBUF_" "Protobuf_" Camel ${UPPER})
38           if (NOT DEFINED ${Camel})
39               set(${Camel} ${${UPPER}})
40           endif()
41       endif()
42   endforeach()
43   # end of compatibility block
44
45   if(Protobuf_FOUND)
46     if(TARGET protobuf::libprotobuf)
47       add_library(libprotobuf INTERFACE IMPORTED)
48       set_target_properties(libprotobuf PROPERTIES
49         INTERFACE_LINK_LIBRARIES protobuf::libprotobuf
50       )
51     else()
52       add_library(libprotobuf UNKNOWN IMPORTED)
53       set_target_properties(libprotobuf PROPERTIES
54         IMPORTED_LOCATION "${Protobuf_LIBRARY}"
55         INTERFACE_INCLUDE_DIRECTORIES "${Protobuf_INCLUDE_DIR}"
56         INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${Protobuf_INCLUDE_DIR}"
57       )
58       get_protobuf_version(Protobuf_VERSION "${Protobuf_INCLUDE_DIR}")
59     endif()
60     set(HAVE_PROTOBUF TRUE)
61   endif()
62 endif()
63
64 if(HAVE_PROTOBUF AND PROTOBUF_UPDATE_FILES AND NOT COMMAND PROTOBUF_GENERATE_CPP)
65   find_package(Protobuf QUIET)
66   if(NOT COMMAND PROTOBUF_GENERATE_CPP)
67     message(FATAL_ERROR "PROTOBUF_GENERATE_CPP command is not available")
68   endif()
69 endif()
70
71 if(HAVE_PROTOBUF)
72   list(APPEND CUSTOM_STATUS protobuf)
73   list(APPEND CUSTOM_STATUS_protobuf "    Protobuf:"
74     BUILD_PROTOBUF THEN "build (${Protobuf_VERSION})"
75     ELSE "${Protobuf_LIBRARY} (${Protobuf_VERSION})")
76 endif()