User Tools

Site Tools


Avoiding Circular Dependencies

Many times, you may run into a circular dependency when writing your Elements. This happens when you have two Elements, A and B, where A's Behavior method needs to use B, and B's Behavior method needs to use A. g++ won't allow you to compile code like this witout defining these methods in a certain way. This tutorial will guide you through creating Elements like this.

In the repo, there are two Elements named Element_CheckerForkBlue and Element_CheckerForkRed, which were created to illustrate the correct way to get around this problem. Please use these as a reference when reading this tutorial.

Create **.tcc** files

Each Element involved in this kind of problem needs an associated .tcc file, which is used to define its behavior. Create one of these files per Element in the elements/include directory.

After these are created, we need to attach them to the existing .h files. Just outside of the MFM namespace block, #include the corresponding .tcc file. For instance, in A.h, you need to #include “A.tcc” .

Include dependencies

In each .tcc file, we can now #include the Elements that we wish to reference in our behavior function. For instance, in A.tcc, we need to #include “B.h” .

Move Behavior method

Now, we need to move the Behavior method to our new .tcc file. Then, following the A example, write:

namespace MFM
  template <class CC>
  void Element_A<CC>::Behavior(EventWindow& window) const
     /* Define Behavior for Element_A here. */

Then, in our .h file, we need to change the definition of our Behavior method to a prototype. Simply get rid of the body of the Behavior method and place a semicolon at the end of the line, like this:

virtual void Behavior(EventWindow<CC>& window) const;

Once you do this for both elements, they should now be able to reference each other and compile.


  • Make sure your .h file does NOT #include the Element which causes the circular dependency. Only your .tcc should do this.
  • Your Behavior method might not be the only one with a circular dependency like this. Make sure to define any other methods which do in your .tcc as well.
dev/circular_dependencies.txt · Last modified: 2014/09/22 18:45 by tsmall1