xref: /aosp_15_r20/external/flatbuffers/CMake/CMakeLists_legacy.cmake.in (revision 890232f25432b36107d06881e0a25aaa6b473652)
1# This was the legacy <root>/CMakeLists.txt that supported cmake version 2.8.12.
2# It was originally copied on Jan 30 2022, and is conditionally included in the
3# current <root>/CMakeLists.txt if the cmake version used is older than the new
4# minimum version.
5#
6# Only add to this file to fix immediate issues or if a change cannot be made
7# <root>/CMakeList.txt in a compatible way.
8
9if (POLICY CMP0048)
10  cmake_policy(SET CMP0048 NEW)
11  if(CMAKE_VERSION VERSION_LESS 3.9)
12    project(FlatBuffers
13      VERSION 2.0.0
14      LANGUAGES CXX)
15  else()
16    project(FlatBuffers
17      DESCRIPTION "Flatbuffers serialization library"
18      VERSION 2.0.0
19      LANGUAGES CXX)
20  endif()
21else()
22  project(FlatBuffers)
23endif (POLICY CMP0048)
24
25include(CMake/Version.cmake)
26
27# generate compile_commands.json
28set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
29
30# NOTE: Code coverage only works on Linux & OSX.
31option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF)
32option(FLATBUFFERS_BUILD_TESTS "Enable the build of tests and samples." ON)
33option(FLATBUFFERS_INSTALL "Enable the installation of targets." ON)
34option(FLATBUFFERS_BUILD_FLATLIB "Enable the build of the flatbuffers library"
35       ON)
36option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
37       ON)
38option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
39       OFF)
40option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
41option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \"
42       Requires C++11."
43       OFF)
44option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
45option(FLATBUFFERS_BUILD_SHAREDLIB
46       "Enable the build of the flatbuffers shared library"
47       OFF)
48option(FLATBUFFERS_LIBCXX_WITH_CLANG "Force libc++ when using Clang" ON)
49# NOTE: Sanitizer check only works on Linux & OSX (gcc & llvm).
50option(FLATBUFFERS_CODE_SANITIZE
51      "Add '-fsanitize' flags to 'flattests' and 'flatc' targets."
52      OFF)
53option(FLATBUFFERS_PACKAGE_REDHAT
54       "Build an rpm using the 'package' target."
55       OFF)
56option(FLATBUFFERS_PACKAGE_DEBIAN
57       "Build an deb using the 'package' target."
58       OFF)
59option(FLATBUFFERS_BUILD_CPP17
60       "Enable the build of c++17 test target. \"
61       Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914)  or higher."
62       OFF)
63option(FLATBUFFERS_BUILD_LEGACY
64       "Run C++ code generator with '--cpp-std c++0x' switch."
65       OFF)
66option(FLATBUFFERS_ENABLE_PCH
67       "Enable precompile headers support for 'flatbuffers' and 'flatc'. \"
68        Only work if CMake supports 'target_precompile_headers'. \"
69        This can speed up compilation time."
70       OFF)
71option(FLATBUFFERS_SKIP_MONSTER_EXTRA
72      "Skip generating monster_extra.fbs that contains non-supported numerical\"
73      types." OFF)
74option(FLATBUFFERS_OSX_BUILD_UNIVERSAL
75      "Enable the build for multiple architectures on OS X (arm64, x86_64)."
76      ON)
77
78if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
79    message(WARNING
80    "Cannot build tests without building the compiler. Tests will be disabled.")
81    set(FLATBUFFERS_BUILD_TESTS OFF)
82endif()
83
84if(DEFINED FLATBUFFERS_MAX_PARSING_DEPTH)
85  # Override the default recursion depth limit.
86  add_definitions(-DFLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH})
87  message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}")
88endif()
89
90# Auto-detect locale-narrow 'strtod_l' and  'strtoull_l' functions.
91if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
92  include(CheckCXXSymbolExists)
93
94  set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
95  if(MSVC)
96    check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
97    check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
98  else()
99    check_cxx_symbol_exists(strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
100    check_cxx_symbol_exists(strtoull_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
101  endif()
102  if(FLATBUFFERS_HAS_STRTOF_L AND FLATBUFFERS_HAS_STRTOULL_L)
103    set(FLATBUFFERS_LOCALE_INDEPENDENT 1)
104  endif()
105endif()
106add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
107
108set(FlatBuffers_Library_SRCS
109  include/flatbuffers/allocator.h
110  include/flatbuffers/array.h
111  include/flatbuffers/base.h
112  include/flatbuffers/bfbs_generator.h
113  include/flatbuffers/buffer.h
114  include/flatbuffers/buffer_ref.h
115  include/flatbuffers/default_allocator.h
116  include/flatbuffers/detached_buffer.h
117  include/flatbuffers/flatbuffer_builder.h
118  include/flatbuffers/flatbuffers.h
119  include/flatbuffers/flexbuffers.h
120  include/flatbuffers/hash.h
121  include/flatbuffers/idl.h
122  include/flatbuffers/minireflect.h
123  include/flatbuffers/reflection.h
124  include/flatbuffers/reflection_generated.h
125  include/flatbuffers/registry.h
126  include/flatbuffers/stl_emulation.h
127  include/flatbuffers/string.h
128  include/flatbuffers/struct.h
129  include/flatbuffers/table.h
130  include/flatbuffers/util.h
131  include/flatbuffers/vector.h
132  include/flatbuffers/vector_downward.h
133  include/flatbuffers/verifier.h
134  src/idl_parser.cpp
135  src/idl_gen_text.cpp
136  src/reflection.cpp
137  src/util.cpp
138)
139
140set(FlatBuffers_Compiler_SRCS
141  ${FlatBuffers_Library_SRCS}
142  src/idl_gen_cpp.cpp
143  src/idl_gen_csharp.cpp
144  src/idl_gen_dart.cpp
145  src/idl_gen_kotlin.cpp
146  src/idl_gen_go.cpp
147  src/idl_gen_java.cpp
148  src/idl_gen_ts.cpp
149  src/idl_gen_php.cpp
150  src/idl_gen_python.cpp
151  src/idl_gen_lobster.cpp
152  src/idl_gen_lua.cpp
153  src/idl_gen_rust.cpp
154  src/idl_gen_fbs.cpp
155  src/idl_gen_grpc.cpp
156  src/idl_gen_json_schema.cpp
157  src/idl_gen_swift.cpp
158  src/flatc.cpp
159  src/flatc_main.cpp
160  src/bfbs_gen.h
161  src/bfbs_gen_lua.h
162  include/flatbuffers/code_generators.h
163  src/bfbs_gen_lua.cpp
164  src/code_generators.cpp
165  grpc/src/compiler/schema_interface.h
166  grpc/src/compiler/cpp_generator.h
167  grpc/src/compiler/cpp_generator.cc
168  grpc/src/compiler/go_generator.h
169  grpc/src/compiler/go_generator.cc
170  grpc/src/compiler/java_generator.h
171  grpc/src/compiler/java_generator.cc
172  grpc/src/compiler/python_generator.h
173  grpc/src/compiler/python_generator.cc
174  grpc/src/compiler/swift_generator.h
175  grpc/src/compiler/swift_generator.cc
176  grpc/src/compiler/ts_generator.h
177  grpc/src/compiler/ts_generator.cc
178)
179
180set(FlatHash_SRCS
181  include/flatbuffers/hash.h
182  src/flathash.cpp
183)
184
185set(FlatBuffers_Tests_SRCS
186  ${FlatBuffers_Library_SRCS}
187  src/idl_gen_fbs.cpp
188  tests/test.cpp
189  tests/test_assert.h
190  tests/test_assert.cpp
191  tests/test_builder.h
192  tests/test_builder.cpp
193  tests/native_type_test_impl.h
194  tests/native_type_test_impl.cpp
195  include/flatbuffers/code_generators.h
196  src/code_generators.cpp
197  # file generate by running compiler on tests/monster_test.fbs
198  ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
199  # file generate by running compiler on namespace_test/namespace_test1.fbs
200  ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h
201  ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h
202  # file generate by running compiler on union_vector/union_vector.fbs
203  ${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h
204  # file generate by running compiler on tests/arrays_test.fbs
205  ${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h
206  # file generate by running compiler on tests/native_type_test.fbs
207  ${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h
208  # file generate by running compiler on tests/monster_extra.fbs
209  ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
210  # file generate by running compiler on tests/monster_test.fbs
211  ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
212  # file generate by running compiler on tests/optional_scalars.fbs
213  ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
214)
215
216set(FlatBuffers_Tests_CPP17_SRCS
217  ${FlatBuffers_Library_SRCS}
218  tests/test_assert.h
219  tests/test_assert.cpp
220  tests/cpp17/test_cpp17.cpp
221  # file generate by running compiler on tests/monster_test.fbs
222  ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h
223  ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
224  ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h
225  ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
226)
227
228set(FlatBuffers_Sample_Binary_SRCS
229  include/flatbuffers/flatbuffers.h
230  samples/sample_binary.cpp
231  # file generated by running compiler on samples/monster.fbs
232  ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
233)
234
235set(FlatBuffers_Sample_Text_SRCS
236  ${FlatBuffers_Library_SRCS}
237  samples/sample_text.cpp
238  # file generated by running compiler on samples/monster.fbs
239  ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
240)
241
242set(FlatBuffers_Sample_BFBS_SRCS
243  ${FlatBuffers_Library_SRCS}
244  samples/sample_bfbs.cpp
245  # file generated by running compiler on samples/monster.fbs
246  ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
247)
248
249set(FlatBuffers_GRPCTest_SRCS
250  include/flatbuffers/flatbuffers.h
251  include/flatbuffers/grpc.h
252  include/flatbuffers/util.h
253  src/util.cpp
254  tests/monster_test.grpc.fb.h
255  tests/test_assert.h
256  tests/test_builder.h
257  tests/monster_test.grpc.fb.cc
258  tests/test_assert.cpp
259  tests/test_builder.cpp
260  grpc/tests/grpctest.cpp
261  grpc/tests/message_builder_test.cpp
262  # file generate by running compiler on tests/monster_test.fbs
263  ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
264)
265
266# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
267# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
268
269if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
270  # do not apply any global settings if the toolchain
271  # is being configured externally
272  message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
273elseif(CMAKE_COMPILER_IS_GNUCXX)
274  if(CYGWIN)
275    set(CMAKE_CXX_FLAGS
276      "${CMAKE_CXX_FLAGS} -std=gnu++11")
277  else(CYGWIN)
278    set(CMAKE_CXX_FLAGS
279      "${CMAKE_CXX_FLAGS} -std=c++0x")
280  endif(CYGWIN)
281  set(CMAKE_CXX_FLAGS
282    "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
283  set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
284  if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4)
285    if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
286      set(CMAKE_CXX_FLAGS
287        "${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2")
288    endif()
289    set(CMAKE_CXX_FLAGS
290      "${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
291  endif()
292
293  # Certain platforms such as ARM do not use signed chars by default
294  # which causes issues with certain bounds checks.
295  set(CMAKE_CXX_FLAGS
296    "${CMAKE_CXX_FLAGS} -fsigned-char")
297
298# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually
299# matches as Clang in its Compiler Id :)
300# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate...
301elseif(MSVC)
302  # Visual Studio pedantic build settings
303  # warning C4512: assignment operator could not be generated
304  # warning C4316: object allocated on the heap may not be aligned
305  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
306
307  if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
308    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS")
309  endif()
310
311elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
312  if(APPLE)
313    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
314
315    if(FLATBUFFERS_OSX_BUILD_UNIVERSAL)
316      set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
317    endif()
318  else()
319    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
320  endif()
321
322  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
323  set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
324  if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
325    list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
326  endif()
327  if(FLATBUFFERS_LIBCXX_WITH_CLANG)
328    if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
329      set(CMAKE_CXX_FLAGS
330          "${CMAKE_CXX_FLAGS} -stdlib=libc++")
331    endif()
332    if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR
333            "${CMAKE_SYSTEM_NAME}" MATCHES "Linux"))
334      set(CMAKE_EXE_LINKER_FLAGS
335          "${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
336    endif()
337  endif()
338
339  # Certain platforms such as ARM do not use signed chars by default
340  # which causes issues with certain bounds checks.
341  set(CMAKE_CXX_FLAGS
342    "${CMAKE_CXX_FLAGS} -fsigned-char")
343
344endif()
345
346# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
347if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
348  message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
349  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
350endif()
351message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
352
353if(FLATBUFFERS_CODE_COVERAGE)
354  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
355  set(CMAKE_EXE_LINKER_FLAGS
356      "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage")
357endif()
358
359function(add_fsanitize_to_target _target _sanitizer)
360  if(WIN32)
361    target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
362    message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}")
363  else()
364    # FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
365    # List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
366    if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
367      ((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
368    )
369      set(_sanitizer_flags "=address,undefined")
370      if(_sanitizer MATCHES "=.*")
371        # override default by user-defined sanitizer list
372        set(_sanitizer_flags ${_sanitizer})
373      endif()
374      target_compile_options(${_target} PRIVATE
375        -g -fsigned-char -fno-omit-frame-pointer
376        "-fsanitize${_sanitizer_flags}")
377      target_link_libraries(${_target} PRIVATE
378        "-fsanitize${_sanitizer_flags}")
379      set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
380      message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
381    endif()
382  endif()
383endfunction()
384
385function(add_pch_to_target _target _pch_header)
386  if(COMMAND target_precompile_headers)
387    target_precompile_headers(${_target} PRIVATE ${_pch_header})
388    if(NOT MSVC)
389      set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
390    endif()
391  endif()
392endfunction()
393
394if(BIICODE)
395  include(biicode/cmake/biicode.cmake)
396  return()
397endif()
398
399include_directories(include)
400include_directories(grpc)
401
402if(FLATBUFFERS_BUILD_FLATLIB)
403  add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
404  # Attach header directory for when build via add_subdirectory().
405  target_include_directories(flatbuffers INTERFACE
406    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
407  target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
408  if(FLATBUFFERS_ENABLE_PCH)
409    add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
410  endif()
411endif()
412
413if(FLATBUFFERS_BUILD_FLATC)
414  add_executable(flatc ${FlatBuffers_Compiler_SRCS})
415  if(FLATBUFFERS_ENABLE_PCH)
416    add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
417  endif()
418  target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
419  if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
420    add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
421  endif()
422  if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
423    set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
424  endif()
425  if(MSVC)
426    # Make flatc.exe not depend on runtime dlls for easy distribution.
427    target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/MT>)
428  endif()
429  if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
430    target_link_libraries(flatc PRIVATE -static)
431  endif()
432endif()
433
434if(FLATBUFFERS_BUILD_FLATHASH)
435  add_executable(flathash ${FlatHash_SRCS})
436endif()
437
438if(FLATBUFFERS_BUILD_SHAREDLIB)
439  add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
440
441  # Shared object version: "major.minor.micro"
442  # - micro updated every release when there is no API/ABI changes
443  # - minor updated when there are additions in API/ABI
444  # - major (ABI number) updated when there are changes in ABI (or removals)
445  set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR})
446  set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
447  set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
448                        SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}"
449                        VERSION "${FlatBuffers_Library_SONAME_FULL}")
450  if(FLATBUFFERS_ENABLE_PCH)
451    add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h)
452  endif()
453endif()
454
455# Global list of generated files.
456# Use the global property to be independent of PARENT_SCOPE.
457set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
458
459function(get_generated_output generated_files)
460  get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
461  set(${generated_files} ${tmp} PARENT_SCOPE)
462endfunction(get_generated_output)
463
464function(register_generated_output file_name)
465  get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
466  list(APPEND tmp ${file_name})
467  set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp})
468endfunction(register_generated_output)
469
470function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
471  if(FLATBUFFERS_BUILD_LEGACY)
472    set(OPT ${OPT};--cpp-std c++0x)
473  else()
474    # --cpp-std is defined by flatc default settings.
475  endif()
476  message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'")
477  get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
478  string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
479  add_custom_command(
480    OUTPUT ${GEN_HEADER}
481    COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
482            --cpp --gen-mutable --gen-object-api --reflect-names
483            --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
484            ${OPT}
485            -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
486            -o "${SRC_FBS_DIR}"
487            "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
488    DEPENDS flatc
489    COMMENT "Run generation: '${GEN_HEADER}'")
490  register_generated_output(${GEN_HEADER})
491endfunction()
492
493function(compile_flatbuffers_schema_to_cpp SRC_FBS)
494  compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
495endfunction()
496
497function(compile_flatbuffers_schema_to_binary SRC_FBS)
498  message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
499  get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
500  string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
501  # For details about flags see generate_code.py
502  add_custom_command(
503    OUTPUT ${GEN_BINARY_SCHEMA}
504    COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
505            -b --schema --bfbs-comments --bfbs-builtins
506            --bfbs-filenames ${SRC_FBS_DIR}
507            -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
508            -o "${SRC_FBS_DIR}"
509            "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
510    DEPENDS flatc
511    COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'")
512  register_generated_output(${GEN_BINARY_SCHEMA})
513endfunction()
514
515function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
516  if(FLATBUFFERS_BUILD_LEGACY)
517    set(OPT ${OPT};--cpp-std c++0x)
518  else()
519    # --cpp-std is defined by flatc default settings.
520  endif()
521  message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
522  get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
523  string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
524  # For details about flags see generate_code.py
525  add_custom_command(
526          OUTPUT ${GEN_BFBS_HEADER}
527          COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
528          --cpp --gen-mutable --gen-object-api --reflect-names
529          --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
530          ${OPT}
531          --bfbs-comments --bfbs-builtins --bfbs-gen-embed
532          --bfbs-filenames ${SRC_FBS_DIR}
533          -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
534          -o "${SRC_FBS_DIR}"
535          "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
536          DEPENDS flatc
537          COMMENT "Run generation: '${GEN_BFBS_HEADER}'")
538  register_generated_output(${GEN_BFBS_HEADER})
539endfunction()
540
541# Look if we have python 3.5 installed so that we can run the generate code
542# python script after flatc is built.
543find_package(PythonInterp 3.5)
544
545if(PYTHONINTERP_FOUND AND
546  # Skip doing this if the MSVC version is below VS 12.
547  # https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
548  (NOT MSVC OR MSVC_VERSION GREATER 1800))
549  set(GENERATION_SCRIPT ${PYTHON_EXECUTABLE} scripts/generate_code.py)
550  if(FLATBUFFERS_BUILD_LEGACY)
551    # Need to set --cpp-std c++-0x options
552    set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x)
553  endif()
554  if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
555    set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra)
556  endif()
557  add_custom_command(
558    TARGET flatc
559    POST_BUILD
560    COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}"
561    WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
562    COMMENT "Running ${GENERATION_SCRIPT}..."
563    VERBATIM)
564else()
565  message("No Python3 interpreter found! Unable to generate files automatically.")
566endif()
567
568if(FLATBUFFERS_BUILD_TESTS)
569  file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
570  file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
571
572  # TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
573  compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
574  compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
575  compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
576  compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
577  compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings")
578  compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
579  compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
580  compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
581  compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
582  compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
583  if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
584    compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
585  endif()
586  include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
587  add_executable(flattests ${FlatBuffers_Tests_SRCS})
588  add_dependencies(flattests generated_code)
589  set_property(TARGET flattests
590    PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
591    FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
592  if(FLATBUFFERS_CODE_SANITIZE)
593    add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
594  endif()
595
596  compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
597  compile_flatbuffers_schema_to_binary(samples/monster.fbs)
598  include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
599  add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
600  add_dependencies(flatsamplebinary generated_code)
601  add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
602  add_dependencies(flatsampletext generated_code)
603  add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
604  add_dependencies(flatsamplebfbs generated_code)
605
606  if(FLATBUFFERS_BUILD_CPP17)
607    # Don't generate header for flattests_cpp17 target.
608    # This target uses "generated_cpp17/monster_test_generated.h"
609    # produced by direct call of generate_code.py script.
610    add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
611    add_dependencies(flattests_cpp17 generated_code)
612    target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
613    target_compile_definitions(flattests_cpp17 PRIVATE
614      FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
615      FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1
616    )
617    if(FLATBUFFERS_CODE_SANITIZE)
618      add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
619    endif()
620  endif(FLATBUFFERS_BUILD_CPP17)
621endif()
622
623if(FLATBUFFERS_BUILD_GRPCTEST)
624  if(CMAKE_COMPILER_IS_GNUCXX)
625    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow")
626  endif()
627  if(NOT GRPC_INSTALL_PATH)
628    message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
629  endif()
630  if(NOT PROTOBUF_DOWNLOAD_PATH)
631    message(SEND_ERROR "PROTOBUF_DOWNLOAD_PATH variable is not defined. See grpc/README.md")
632  endif()
633  INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include)
634  INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
635  find_package(Threads REQUIRED)
636  list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH})
637  find_package(absl CONFIG REQUIRED)
638  find_package(protobuf CONFIG REQUIRED)
639  find_package(gRPC CONFIG REQUIRED)
640  add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
641  add_dependencies(grpctest generated_code)
642  target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
643  if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
644    # GRPC test has problems with alignment and will fail under ASAN/UBSAN.
645    # add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
646  endif()
647endif()
648
649
650if(FLATBUFFERS_INSTALL)
651  include(GNUInstallDirs)
652
653  install(DIRECTORY include/flatbuffers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
654
655  set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
656
657  configure_file(CMake/FlatBuffersConfigVersion.cmake.in FlatBuffersConfigVersion.cmake @ONLY)
658  install(
659      FILES "CMake/FlatBuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatBuffersConfigVersion.cmake"
660      DESTINATION ${FB_CMAKE_DIR}
661  )
662
663  if(FLATBUFFERS_BUILD_FLATLIB)
664    if(CMAKE_VERSION VERSION_LESS 3.0)
665      install(
666        TARGETS flatbuffers EXPORT FlatBuffersTargets
667        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
668      )
669    else()
670      install(
671        TARGETS flatbuffers EXPORT FlatBuffersTargets
672        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
673        INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
674      )
675    endif()
676
677    install(EXPORT FlatBuffersTargets
678      FILE FlatBuffersTargets.cmake
679      NAMESPACE flatbuffers::
680      DESTINATION ${FB_CMAKE_DIR}
681    )
682  endif()
683
684  if(FLATBUFFERS_BUILD_FLATC)
685    install(
686      TARGETS flatc EXPORT FlatcTargets
687      RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
688    )
689
690    install(
691      EXPORT FlatcTargets
692      FILE FlatcTargets.cmake
693      NAMESPACE flatbuffers::
694      DESTINATION ${FB_CMAKE_DIR}
695    )
696  endif()
697
698  if(FLATBUFFERS_BUILD_SHAREDLIB)
699    if(CMAKE_VERSION VERSION_LESS 3.0)
700      install(
701        TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
702        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
703        RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
704        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
705      )
706    else()
707      install(
708        TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
709        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
710        RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
711        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
712        INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
713      )
714    endif()
715
716  install(
717      EXPORT FlatBuffersSharedTargets
718      FILE FlatBuffersSharedTargets.cmake
719      NAMESPACE flatbuffers::
720      DESTINATION ${FB_CMAKE_DIR}
721    )
722  endif()
723
724  if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB)
725      configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY)
726      install(
727        FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc"
728        DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
729      )
730  endif()
731endif()
732
733if(FLATBUFFERS_BUILD_TESTS)
734  enable_testing()
735
736  add_test(NAME flattests COMMAND flattests)
737  if(FLATBUFFERS_BUILD_CPP17)
738    add_test(NAME flattests_cpp17 COMMAND flattests_cpp17)
739  endif()
740  if(FLATBUFFERS_BUILD_GRPCTEST)
741    add_test(NAME grpctest COMMAND grpctest)
742  endif()
743endif()
744
745# This target is sync-barrier.
746# Other generate-dependent targets can depend on 'generated_code' only.
747get_generated_output(fbs_generated)
748if(fbs_generated)
749  # message(STATUS "Add generated_code target with files:${fbs_generated}")
750  add_custom_target(generated_code
751    DEPENDS ${fbs_generated}
752    COMMENT "All generated files were updated.")
753endif()
754
755include(CMake/BuildFlatBuffers.cmake)
756
757if(UNIX)
758    # Use of CPack only supported on Linux systems.
759    if(FLATBUFFERS_PACKAGE_DEBIAN)
760        include(CMake/PackageDebian.cmake)
761        include(CPack)
762    endif()
763    if (FLATBUFFERS_PACKAGE_REDHAT)
764        include(CMake/PackageRedhat.cmake)
765        include(CPack)
766    endif()
767endif()
768
769# Include for running Google Benchmarks.
770if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13)
771  add_subdirectory(benchmarks)
772endif()
773
774# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare
775add_library(FlatBuffers INTERFACE)
776add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
777target_include_directories(
778  FlatBuffers
779  INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
780            $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)
781