Jake Wilson
Jake Wilson

Reputation: 91213

Circularly declaring Preprocessor directives? Or defines before includes?

I'm a bit new to C++, so bear with me. I'm trying to figure out where exactly to place my #defines and #includes in my project. I have something like this:

main.h

#include "other.h"

#define MAX_GROUPS 100

struct Cat
{
    int something[MAX_GROUPS];
}

In other.h I also need to use MAX_GROUPS, so do I also define MAX_GROUPS in other.h like this:

other.h

#define MAX_GROUPS 100

struct Other
{
     int taco[MAX_GROUPS];
}

The problem is that I'm defining a constant more than one place. I want to keep it all together.

Alternatively, do I reinclude main.h?

other.h

#include "main.h"

struct Other
{
     int taco[MAX_GROUPS];
}

The problem here I think its that is creates like a circular dependancy thing. main.h includes other.h which includes main.h which includes other.h which includes etc...

What is the best way to setup the defines and includes for a project so that things sorta cascade down to other included files? Is it common practice to simply do all your defines before your includes?

Upvotes: 0

Views: 2114

Answers (4)

Brian Hooper
Brian Hooper

Reputation: 22074

You could also protect your constants against redefinition case by case...

#ifndef MAX_GROUPS
#define MAX_GROUPS 100
#endif

Upvotes: 0

vij
vij

Reputation: 46

Generally, you should put the defines inside whichever header is relevant -- or where it is primarily used. In this case, you should put MAX_GROUPS inside other.h. By including other.h in main.h, the define will also be picked up (as mentioned by jwismar).

For bigger projects, however, you'd be better off creating a header file containing only your manifest constants (defines) and just include that where needed.

Upvotes: 0

jwismar
jwismar

Reputation: 12268

Because main.h #includes other.h, it doesn't need to #define MAX_GROUPS again. It'll pick up that definition from the inclusion.

Upvotes: 2

janm
janm

Reputation: 18349

Minimising circular dependencies is very important in maintaining your project. For an extended discussion, see "Large Scale C++ Software Design" by John Lakos.

To avoid the specific problem you are having, define values in one header file, and include that header file in every file that needs it. To avoid problems with multiple definitions, use include guards:

#ifndef HEADER_THING_H
#define HEADER_THING_H

/* Rest of the header file goes here. */

#endif

That way if it is already included, it is harmless.

Upvotes: 5

Related Questions