Use generated images in a Sphinx document with CMake

Viewed 106

How do I include an image in a Sphinx .rst file that has been automatically generated outside the Sphinx source directory?

I build a Sphinx project using CMake. One of the Sphinx source files includes a PDF image that is generated by a separate target in the CMake project. As far as I understand, one should not generate outputs from a CMake build process inside the CMake source tree. (I think this can be justified by the fact that different CMake build configurations generate different outputs). Thus, the input to the Sphinx build cannot be in the Sphinx source tree and the relative path to the the image to include in the Sphinx document is unknown when writing the Sphinx code.

How can I solve this?

1 Answers

Here's a sketch of a solution (too big for a comment):

  1. You could call Sphinx from CMake with an environment variable set that points to the build (sub)directory where your generated images are stored. Pass this with add_custom_command and ${CMAKE_COMMAND} -E env ...
  2. Your Sphinx config could read that environment variable (``) and add the result to html_static_path:
import os

# ...

html_static_path = [
   # ...
   os.getenv('BUILD_DIR'),
]
  1. Then ensure that you have a custom target (call it generate_doc_images) to drive the custom command(s) that generate your images. Use add_dependencies to make sure that the image generators run before Sphinx.

If you provide an MRE that gets you almost all the way there, I can help you wire things up correctly.

Related