3

I have a VECTOR struct that holds 3 integers, i, j, and k. I need to utilize this struct in more than one header file. Is it considered bad practice to move all #defines, and structs, all constants to a separate header file labeled, "Constants.h", or should I define the same struct in each header file where I currently use it?

user680725
  • 103
  • 2
  • 9
  • 1
    This is what a header file for. Declare the struct within a header file and include this header in other files. – ali_bahoo Dec 22 '11 at 08:15

2 Answers2

6

It is very good practice to move definitions into header-files, so that they can be used in different compilation-units. This ensures that all your compilation-units always use the same definitions of your classes and constants (see here for a more elaborate explanation with examples).

It is, however, bad practice to put them all in one header-file. This makes all compilation-units that use this header-file recompile, even on completely unrelated changes. You should group things together that belong together in some sense - unrelated things should be in different headers. It is sometimes useful to provide one header that includes all, for convenience, but such a feature should only be used for quick prototyping or after careful consideration of the implications - compilation-times can quickly become very long. This answer lists some ideas on how to organize your headers.

Note that you should try to avoid macros for constants in C++ - prefer static const T, e.g.:

static const int foo = 42;

Macros are not typesafe and can introduce subtle bugs due to the way are expanded. This question lists some cases when macros are actually useful.

Community
  • 1
  • 1
Björn Pollex
  • 70,106
  • 28
  • 177
  • 265
0

It's not a bad practice at all. It's generally a good practice to re-use code.

Jem
  • 2,146
  • 17
  • 24