Currently building Tensorflow into a C++ project requires several steps and a modest amount of debugging. In this post I'm going to document how I've managed to build tensorflow in my own C++ projects, and update these instructions as and when I find better ways of doing this.
The steps are roughly as follows:
- Download the Tensorflow source and dependencies
- Build the Tensorflow static library
- Build the static nsync library (required by Tensorflow)
- Set the include paths for headers and the static libraries
These instructions have only been tested on macOS but should also work for Linux. Unfortunately I can't comment on how this will work on Windows.
If at any point you make a mistake with the build or need to reset your local repo, the following commands will forcefully remove any changes in your tensorflow directory:
git reset --hard origin/r1.7 (or another later release tag)
git checkout -f r1.7
1. Download the Tensorflow source and dependencies
Firstly, if you haven't already you'll need to download the source code for Tensorflow. Go to the directory you want to clone the source into, then run:
git clone https://github.com/tensorflow/tensorflow
git checkout r1.7 (or another later release tag)
directory in Tensorflow provides many components that you'll need to build the static library, and provides a makefile and script to download dependencies.
I'd recommend having a look at the makefile in this part of the project as it has some useful information.
Now we need to download some dependencies. From the top directory in the Tensorflow project, run the following command:
2. Build the Tensorflow static library
From the top directory in the Tensorflow project, run the following command:
This will provide a static library in:
3. Build the static nsync library
Nsync is required by projects that link against Tensorflow, so we now need to build it. Go to tensorflow/contrib/makefile/downloads/nsync/builds/<platform> and run make. This will build libnsync.a which you can link your project against.
4. Set the include paths for headers and the static libraries
When building your projects there are some includes paths required for nsync, protobuf, eigen, and Tensorflow itself. Either set these in your IDE or makefile:
And the libraries to link against:
You'll also need to add one of the following linker flags depending on your platform:
Linux: -Wl,--allow-multiple-definition -Wl,--whole-archive
This will prevent the runtime error `Not found: No session factory registered for the given session options`, which is caused by the linker removing symbols that are actually needed