简体   繁体   中英

How to use TensorFlow C++ api as a shared library with bazel?

Now I can build TensorFlow C++ api as a shared library refer to make shared libraries with Bazel at Tensorflow , libtensorflow_cc.so and libtensorflow_framework.so file can be locate at bazel-bin/tensorflow .

I am not familiar with bazel, how should I use those TF shared library with bazel to write C++ code, could you please provide an example like that links ?

Bazel is just a tool like make or cmake. For compiling your code using bazel, you have to create a build file BUILD . Suppose that your code is at, eg, tensorflow/tensorflow/test/code.cpp :

#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"

using namespace tensorflow;

...

create a BUILD file (in the same folder) containing contents like this:

cc_binary(
    name = "code",
    srcs = ["code.cc"],
    deps = [
        "//tensorflow/core:tensorflow",
    ]
)

then configure and compile your code using command:

cd tensorflow
./configure
cd tensorflow/tensorflow/test
bazel build :code

An executable will be available at bazel-bin folder in tensorflow root directory.


However, the compiled code can be huge (> 100 MB) so it is better to link your code to TensorFlow's shared libraries. Both libtensorflow_cc.so and libtensorflow_framework.so can be used in your codes like other shared library files ( .so ). The following is a common way to do so.

  1. Compile the C++ code using the header library file ( .h ) using the shared library ( libtensorflow_cc.so or/and libtensorflow_framework.so ), eg,
     g++ -fPIG -Wall -o code code.cpp -L/usr/lib/libtensorflow_cc.so -ltensorflow_cc
  2. Set LD_LIBRARY_PATH to the location of .so files
  3. Use ldd your_code.out to confirm if your executable is properly linked to a shared library.
  4. Run the executable (eg ./your_code.out )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM