You are not logged in.

#1 2010-10-07 20:28:37

Basu
Member
From: Cornell University
Registered: 2006-12-15
Posts: 296
Website

Where to put #includes?

I'm writing my first really large scale C program and I'm wondering where you all include your header files. On previous projects I've followed the pattern of having the .h file for each .c file have all the #includes. The .c then just #includes the .h with the same name. It seemed like a pretty logical way of doing things. But today I came across Rob Pike's guidelines on writing C code where he suggest just the opposite: all #includes should be in .c files. I'm not sure I quite agree with his argument that pushing the decision of what to include onto the end programmer is a good thing.

What style do you guys follow and why?


The Bytebaker -- Computer science is not a science and it's not about computers
Check out my open source software at Github

Offline

#2 2010-10-07 22:28:01

stqn
Member
Registered: 2010-03-19
Posts: 1,191
Website

Re: Where to put #includes?

What about putting the #includes where they are needed? smile

You should strive to minimize #includes in header files in order to reduce compilation times (and useless dependencies in the case of someone linking a .o of your code.)

Offline

#3 2010-10-08 01:19:37

jdarnold
Member
From: Medford MA USA
Registered: 2009-12-15
Posts: 485
Website

Re: Where to put #includes?

Yup, I agree with Mr. Pike - just include .h files that your .h file needs. Include everything else in the .c file. For C++, you can minimize the need to .h files in .h files by using the following idiom:

class Foobar* foobar_;

This way you don't need a full definition of the class. The compiler is happy to know it is a pointer. The .cpp file that uses it can include the correct header file to get the class definition.

In practice though, given the speed of compilation, it's not worth worrying about, esp. if you start all your .h files thusly:

#if !defined(FOOBAR_H)
#define FOOBAR_H

...

#endif

Sure, you cost a few extra cycles to see it is already loaded, but you're right out of there.

Last edited by jdarnold (2010-10-08 01:20:07)

Offline

Board footer

Powered by FluxBB