hyperboreean
hyperboreean

Reputation: 8333

proper C refactoring

I have the following files: a.h, a.c, b1.c, b2.c and in both b1 and b2 I have some macro definitions which are identical.

Is it ok if I move them in a.h or is it more common to leave them in the file where they are being used ? Which way is the proper way to do it in C ?

Upvotes: 4

Views: 208

Answers (5)

Graham Perks
Graham Perks

Reputation: 23390

If b1 and b2 actually refer to the same thing (if you changed one, you'd have to change it in the other), then the header is the appropriate place to put those definitions. Then you only need change it in one place, and can't accidentally forget a place to change it.

Upvotes: 1

Brian Campbell
Brian Campbell

Reputation: 332816

It is common to move macro definitions which are shared between files into a header which both of those files include. You should make sure that the file you move that definition into is a sensible file for it to be in; don't move it into a completely unrelated header just because it's included in both files. If there is no logical related header file for both b1.c and b2.c, perhaps you ought to create a b.h to be shared between them.

Upvotes: 8

nmichaels
nmichaels

Reputation: 50941

If the macro definitions don't stomp over valuable namespace, stick them in the header most appropriate. If that's a.h, go for it. It sounds like it's more likely to be b.h.

Upvotes: 1

Will Hartung
Will Hartung

Reputation: 118611

Whatever floats your boat.

If a.h has anything to do with this macro, then that's a fine place. If it's being put there "just because" a.h happens to be already included in b1.c and b2.c, that's not really a design issue, rather it's a "convenience" issue. Arguably that's better than duplicating it, but ideally if it's unrelated to a.h perhaps you could put it in b.h (since it related to b) or handymacros.h (since it's not really b specific, but a doesn't happen to use it).

Upvotes: 1

identity
identity

Reputation: 969

I'd say that there's nothing wrong with moving the macro to a.h if it is included in both code files, provided that it makes sense for all files to include a.h.

Upvotes: 1

Related Questions