2

I am still getting used to working with C/C++ and I don't want to 'overinclude' libraries.

I have a header where I would like to place methods for reading input data as well as those variables which I call ofun.h because it handles information pertaining to the objective function I am trying to optimize. In this header, I need the name of the data defined as string data_name;.

Should I #include <string> inside this header file? If this happens and I include <string> in another header file, say file_io.h, and then in my main routine I call

#include <string>
#include "ofun.h"
#include "file_io.h"

will this cause problems? If so, what is the best way/place to include standard libraries like this so that they don't collide?

1
  • 1
    The #ifndef..#endif guards will take care of it. It is only a problem if you are compiling on a very slow device (eg floppy disk). Commented Jun 5, 2014 at 14:36

3 Answers 3

6

If anything within the header needs declarations included within <string>, I'd go ahead and include it within the header file. The best practice to ensure header files don't collide is to use include guards: http://en.wikipedia.org/wiki/Include_guard. Basically, you surround the declarations in your header with this:

#ifndef OFUN_H_
#define OFUN_H_

//your header here

#endif

This is, for example what you'd put in ofun.h. All of the standard library header files already have the include guard in them, you just need to make sure you put them in your own header files.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, I'm using include guardes on __ofun__ but wasn't sure it was guarding against double includes of <string>
All standard C++ headers have the include guard in them, so you can even type in #include <string> three times in a row in the same file, and nothing bad will happen. Obviously, though, that won't actually accomplish anything, so stick with only including it once.
Please don't suggest using reserved names for include guards.
@MikeSeymour: I didn't do that, did I? I'm not sure what you mean.
@wolfPack88: Names like _OFUN_H_, beginning with an underscore followed by an upper-case letter, are reserved. See the question I linked to for details.
|
1

If you need this library in ofun.h for example, then include it in there. if you need it both in ofun.h and in the file including ofun.h , you can include it only in ofun.h.

Comments

1

Don't be afraid. For consistence sake, put every header you need in every file which uses identifiers declared in such header, even if a chain of includes repeats headers.

Guards will be care of you about that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.