Doxygen copydoc tag to reuse code examples

sharkin picture sharkin · Feb 15, 2011 · Viewed 8.5k times · Source

I want to reuse a block of example code using the \copydoc tag.

To explain the problem. Let's say I have two documented functions:

/** Aquires resource. */
Resource* AquireResource( int id );

/** Releases resource.*/
void ReleaseResource( Resource* res );

In many cases I want to put in a small code example of how to use the function in a context, which often involves using a range of functions which all might be sufficiently depicted by the same code example, for instance:

/** Aquires resource.
 *
 * \par Example:
 * \code
 * Resource* res = AquireResource( 42 );
 * ReleaseResource( res );
 * \endcode
 */
Resource* AquireResource( int id );

/** Releases resource.
 *
 * \par Example:
 * \code
 * Resource* res = AquireResource( 42 );
 * ReleaseResource( res );
 * \endcode
 */
void ReleaseResource( Resource* res );

So the code example is duplicated, not good. I want to use copydoc, something like this:

/** \page ResourceExampleTag
 * \code
 * Resource* res = AquireResource( 42 );
 * ReleaseResource( res );
 * \endcode
 */    

/** Aquires resource.
 *
 * \par Example:
 * \copydoc ResourceExampleTag
 */
Resource* AquireResource( int id );

/** Releases resource.
 *
 * \par Example:
 * \copydoc ResourceExampleTag
 */
void ReleaseResource( Resource* res );

I.e. code example in one place, reused in other places.

This is actually as far as I have gotten, but I'm not satisfied with it since I don't know how to hide the dummy page 'ResourceExampleTag' I'm creating to copy from. So somewhere in the resulting documentation there's a page with some code completely out of context. As far as I can see the thing here is to find a tag which can be referenced by copydoc and which doesn't render any content on itself. However, that's just my line of thought, there might be far better ones.

I can also mention that I (for several reasons I won't bother to go into) don't wish to use the \example tag with external example code files.

Thanks.

Answer

rve picture rve · Feb 7, 2012

This works for me:

class MyClass
{
  public:
    /**
     * @class hide_commonstuff
     * @par Example:
     * @code
     * The common example
     * @endcode
     */

    /**
     * First function.
     *
     * @copydoc hide_commonstuff
     */
    void first();

    /**
     * Second function.
     *
     * @copydoc hide_commonstuff
     */
    void second();
};

and then in the doxygen configuration you set EXCLUDE_SYMBOLS = hide_*

The the documentation is copied from the hide_commonstuff but this class is not shown in the class list.

Also: there needs to be a blank line before @copydoc or else it does not work (sometimes, not always...)