无需安装tensorflow,使用c++直接编译使用tensorflow api.

c++使用tensorflow,如果通过自己编译安装整个tensorflow, 那么写完c++程序直接使用bazel构造工具就可以编译。
** 但在具体的项目应用中,为了方便,我们往往需要一个独立可融入目前系统的编译方法。而不是每次都要去bazel构建.
所以,下文演示代码如何直接使用编译好的tensorflow.so调用api。不需安装整个tensorflow**。
里面的相关头文件是我从自己编译的tensorflow扒出来的。使用时直接同步git上面的代码下来,就可以自己写c++并调用tensorflow的api了。

链接:https://github.com/toniz/tensorflow-cpp-example

目前github上的版本是1.2.1,如果需要使用更新版本的tensorflow.so,找到新版本的相关文件夹和文件,替换即可。

tensorflow cpp compile example. Using tensorflow.so. can run without install tensorflow.


Compile Requirement

tensorflow.so is building in GCC5.4.0 and glibc-2.23

  • need GCC >=5.4.0
  • need GLIBC >= 2.23

Compile

  • g++ -std=c++11 -Iinclude -Llib test.cpp -ltensorflow_cc -o exec
  • g++ -std=c++11 -Iinclude -Llib label_image.cc -ltensorflow_cc -o label_image

Run

无需安装tensorflow,使用c++直接编译使用tensorflow api._第1张图片
01.jpg

GCC < 5.4.0 && GLIBC < 2.23

Insall GCC 5.4.0

sudo yum install libmpc-devel mpfr-devel gmp-devel
sudo yum install zlib-devel*
curl ftp://ftp.gnu.org/pub/gnu/gcc/gcc-5.4.0/gcc-5.4.0.tar.bz2 -O
tar xvfj gcc-5.4.0.tar.bz2    
cd gcc-5.4.0
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8
sudo make install

found libstdc++.so.6.0.21 installed in your system.

Insall GLIBC 2.26

wget http://mirror.csclub.uwaterloo.ca/gnu/libc/glibc-2.26.tar.gz
tar -zxvf glibc-2.26.tar.gz 
mkdir glibc-build
cd glibc-build
../glibc-2.26/configure --prefix=/usr/lib64/glibc-2.26 
make -j 8
make install

found /usr/lib64/glibc-2.26/lib/libc.so installed

Compile

g++ -std=c++11 -Wl,-rpath='/usr/lib64/glibc-2.26/lib' -Wl,--dynamic-linker='/usr/lib64/glibc-2.26/lib/ld-linux-x86-64.so.2' -Iinclude -I'/usr/lib64/glibc-2.26/include' -Llib -L '/usr/lib64/glibc-2.26/lib' test.cpp -ltensorflow_cc -o exec 
g++ -std=c++11 -Wl,-rpath='/usr/lib64/glibc-2.26/lib' -Wl,--dynamic-linker='/usr/lib64/glibc-2.26/lib/ld-linux-x86-64.so.2' -Iinclude -I'/usr/lib64/glibc-2.26/include' -Llib -L '/usr/lib64/glibc-2.26/lib' label_image.cc -ltensorflow_cc -o label_image 

Run

export LD_LIBRARY_PATH=./lib:/usr/local/lib64/
无需安装tensorflow,使用c++直接编译使用tensorflow api._第2张图片
02.jpg

libstdc++.so.6.0.21 is in /usr/local/lib64/

源码:
https://github.com/toniz/tensorflow-cpp-example

tensorflow不同版本的so可以使用下面sh脚本下载:

 TF_TYPE="cpu" # Change to "gpu" for GPU support
 OS="linux" # Change to "darwin" for Mac OS
 TARGET_DIRECTORY="/usr/local"
 curl -L \
   "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-${OS}-x86_64-1.4.1.tar.gz" |
   sudo tar -C $TARGET_DIRECTORY -xz

替换项目中的文件使用,可能需要微调,这个我没试过。

你可能感兴趣的:(无需安装tensorflow,使用c++直接编译使用tensorflow api.)