Build doxygen from CMake script

amigo421 picture amigo421 · Jan 19, 2016 · Viewed 16.3k times · Source

I found on the Web a sample cmake file and put it in the /doc subdirectory of my project, where the file myproject.doxgen is also located, containing Doxygen configuration.

I've tested that running doxygen.exe myproject.doxygen produces valid output. I only need to build this into the CMake process. So /doc/CMakeLists.txt is:

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}/../doc/myproject.doxygen)
    set(doxyfile ${CMAKE_CURRENT_BINARY_DIR}/doxyfile)

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

    message("Doxygen build started.")

    add_custom_target(doc
                      COMMAND ${DOXYGEN_EXECUTABLE} ${doxyfile_in}
                      WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc
                      COMMENT "Generating API documentation with Doxygen"
                      VERBATIM)

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

It doesn't work for me, it only copies the original config file into /build/my/project/doc/ and does nothing more.

What I want is to generate the doxygen documentation during my builds; ideally, only when building the Release configuration.

Answer

The way the CMake file you've shown is set up, it creates a target called doc; building that target (such as running make doc) generates the doxymentation. The target is not part of make all (or equivalent); to make it such, add ALL into the custom target creation:

add_custom_target(
  doc ALL
  COMMAND #... everything else as before
)

If you want to limit this target to only build in a particular configuration (as you've mentioned in comments), you can use generator expressions:

add_custom_target(
  doc ALL
  COMMAND $<$<CONFIG:Release>:${DOXYGEN_EXECUTABLE} ${doxyfile_in}>
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc
  COMMENT "Generating API documentation with Doxygen"
  VERBATIM
)

It might happen that some CMake generators do not cope well with an empty COMMAND. With this in mind, the following should be fail-safe:

add_custom_target(
  doc ALL
  COMMAND
    $<$<CONFIG:Release>:${DOXYGEN_EXECUTABLE} ${doxyfile_in}>
    $<$<NOT:$<CONFIG:Release>>:${CMAKE_COMMAND} -E echo "Only done in Release builds">
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc
  COMMENT "Generating API documentation with Doxygen"
  VERBATIM
)