diff --git a/CMakeLists.txt b/CMakeLists.txt index dee2c39a0..af1048dbe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,7 +180,10 @@ include_directories(include) include_directories(grpc) if(FLATBUFFERS_BUILD_FLATLIB) -add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS}) + add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS}) + # CMake > 2.8.11: Attach header directory for when build via add_subdirectory(). + target_include_directories(flatbuffers INTERFACE + $) endif() if(FLATBUFFERS_BUILD_FLATC) diff --git a/docs/source/Building.md b/docs/source/Building.md index 607bd873f..c2faddad2 100644 --- a/docs/source/Building.md +++ b/docs/source/Building.md @@ -41,7 +41,7 @@ running the `android_sample.sh` script. Optionally, you may go to the `flatbuffers/samples/android` folder and build the sample with the `build_apk.sh` script or `ndk_build` / `adb` etc. -## Using FlatBuffers in your own projects. +## Using FlatBuffers in your own projects For C++, there is usually no runtime to compile, as the code consists of a single header, `include/flatbuffers/flatbuffers.h`. You should add the @@ -55,6 +55,31 @@ To see how to include FlatBuffers in any of our supported languages, please view the [Tutorial](@ref flatbuffers_guide_tutorial) and select your appropriate language using the radio buttons. +### Using in CMake-based projects +If you want to use FlatBuffers in a project which already uses CMake, then a more +robust and flexible approach is to build FlatBuffers as part of that project directly. +This is done by making the FlatBuffers source code available to the main build +and adding it using CMake's `add_subdirectory()` command. This has the +significant advantage that the same compiler and linker settings are used +between FlatBuffers and the rest of your project, so issues associated with using +incompatible libraries (eg debug/release), etc. are avoided. This is +particularly useful on Windows. + +Suppose you put FlatBuffers source code in directory `${FLATBUFFERS_SRC_DIR}`. +To build it as part of your project, add following code to your `CMakeLists.txt` file: +```cmake +# Add FlatBuffers directly to our build. This defines the `flatbuffers` target. +add_subdirectory(${FLATBUFFERS_SRC_DIR} + ${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-build + EXCLUDE_FROM_ALL) + +# Now simply link against flatbuffers as needed to your already declared target. +# The flatbuffers target carry header search path automatically if CMake > 2.8.11. +target_link_libraries(own_project_target PRIVATE flatbuffers) +``` +When build your project the `flatbuffers` library will be compiled and linked +to a target as part of your project. + #### For Google Play apps For applications on Google Play that integrate this library, usage is tracked.