Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping Structs/Constants in separate header

Tags:

c++

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?

like image 300
user680725 Avatar asked Jan 23 '26 01:01

user680725


1 Answers

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.

like image 171
Björn Pollex Avatar answered Jan 24 '26 20:01

Björn Pollex