tensorflow目前支持最好的语言还是python,但大部分服务都用C++ or Java开发,一般采用动态链接库(.so)方式调用算法,因此tensorflow的c/c++ API还是有必要熟悉下,而且经过本人测试,相同算法,c接口相比python速度更快。
下面讲解如何让程序调用tensorflow c/c++库
1.编译库
先在github上下载tensorflow源码,执行./configure先配置项目,然后按照这篇博客里写的利用bazel编译动态链接库,编译命令如下
C版本:
bazel build :libtensorflow.so
C++版本:
bazel build :libtensorflow_cc.so
编译成功后,在bazel-bin/tensorflow/目录下会出现libtensorflow.so/libtensorflow_cc.so文件
2.其他依赖
在使用tensorflow c/c++接口时,会有很多头文件依赖、protobuf版本依赖等问题
(1)tensorflow/contrib/makefile目录下,找到build_all_xxx.sh文件并执行,例如准备在linux上使用,就执行build_all_linux.sh文件,成功后会出现一个gen文件夹
(2)把tensorflow和bazel-genfiles文件夹下的头文件都抽取出来放在一个文件夹下面,或者通过cmake把这两个路径添加进include_directories中
(3)tensorflow/contrib/makefile/gen/protobuf/include,也就是(1)中生成的文件夹中的头文件,也需要抽取或者在cmake中包含在include_directories中
3.编写代码
随便编写一段使用tf的代码,例如下面:
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/public/session.h>
#include <iostream>
using namespace std;
using namespace tensorflow;
int main()
{
Session* session;
Status status = NewSession(SessionOptions(), &session);
if (!status.ok()) {
cout << status.ToString() << "\n";
return 1;
}
cout << "Session successfully created.\n";
}
4.生成可执行文件
把libtensorflow_cc.so文件放在lib文件夹下,代码放在src文件夹下,编写cmakelist.txt,具体文件结构如下:
CMakeLists.txt
/src
/lib
/include
/build
下面是一个例子:
cmake_minimum_required (VERSION 2.8.8)
project (tf_example)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -std=c++11 -W")
aux_source_directory(./src DIR_SRCS)
link_directories(./lib)
include_directories(
path_to_tensorflow/tensorflow
path_to_tensorflow/tensorflow/bazel-genfiles
path_to_tensorflow/tensorflow/contrib/makefile/gen/protobuf/include
) add_executable(tf_test ${DIR_SRCS}) target_link_libraries(tf_example tensorflow_cc)
接下来执行命令:
cd build
cmake ..
make
会生成一个tf_test可执行文件,执行无误即大功告成
来源:https://www.cnblogs.com/hrlnw/p/7383951.html