Calling Doxygen from cmake

The following doc/CMakeLists.txt file checks for Doxygen and if found, adds a doc target to the build system.

It also generates a doc/Doxyfile in the build folder, which allows cmake to substitute some variables such as version number, project name, source and destination folder etc.

# add a target to generate API documentation with Doxygen
find_package(Doxygen)
option(BUILD_DOCUMENTATION "Create and install the HTML based API documentation (requires Doxygen)" ${DOXYGEN_FOUND})

if(BUILD_DOCUMENTATION)
    if(NOT DOXYGEN_FOUND)
        message(FATAL_ERROR "Doxygen is needed to build the documentation.")
    endif()

    set(doxyfile_in ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in)
    set(doxyfile ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)

    configure_file(${doxyfile_in} ${doxyfile} @ONLY)

    add_custom_target(doc
        COMMAND ${DOXYGEN_EXECUTABLE} ${doxyfile}
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
        COMMENT "Generating API documentation with Doxygen"
        VERBATIM)

    install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html DESTINATION share/doc)
endif()

This doc/Doxyfile.in extract shows some example cmake variables used. Other values can be used too.

Since cmake uses the full path names in @PROJECT_SOURCE_DIR@, we have to strip some parts of the path using the STRIP_FROM_PATH option.

PROJECT_NAME           = "@CMAKE_PROJECT_NAME@"
PROJECT_NUMBER         = @VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@
STRIP_FROM_PATH        = @PROJECT_SOURCE_DIR@ \
                         @PROJECT_BINARY_DIR@
INPUT                  = @doxy_main_page@ \
                         @PROJECT_SOURCE_DIR@ \
                         @PROJECT_BINARY_DIR@
FILE_PATTERNS          = *.h \
                         *.cc
RECURSIVE              = YES
USE_MDFILE_AS_MAINPAGE = @doxy_main_page@

To change the version number put this in one of your CMakeLists.txt files:

# The project version number.
set(VERSION_MAJOR   0   CACHE STRING "Project major version number.")
set(VERSION_MINOR   0   CACHE STRING "Project minor version number.")
set(VERSION_PATCH   1   CACHE STRING "Project patch version number.")
mark_as_advanced(VERSION_MAJOR VERSION_MINOR VERSION_PATCH)

It is easy to extend this to C/C++ as well. Just have a file pre-processed by cmake using the configure_file() command to generate a config.h file from a template.