In my time with C/C++ I have encountered different ways to handle the file path for the #include directive when including your .h file in your .cpp/.c file. The Google style guide alludes to using part of the file path in your #include. That being said, I currently work on a project (albeit a small one) where a nicely laid out Makefile (for G++) and structure was laid out for me when I "inherited" the code. Namely, there is a directory named /project_name and inside is the Makefile and several sub-directories. For example, /project_name/inc holds the .h files and /project_name/src holds the .cpp files. The Makefile is set to look into each sub-directory to compile the source code.
My question is, given the directory structure and the Makefile, what is the "preferred" method for #include. The two alternatives I am successful with using are listed below.
Are there any other options that I'm missing?
Use neither. Rather, put all your public headers in some hierarchy with a single root. For instance if your project is foo, put all your public headers in, say, include/foo
, but don't hesitate to group your headers per component:
include/foo/io/printer.hh
include/foo/io/reader.hh
include/foo/job/job.hh
include/foo/job/scheduler.hh
Then if your code use only <foo/io/printer.hh>
and so forth, which requires that you pass the proper -I $(top_srcdir)/include
flags during construction of your project. This set-up simplifies things if you have to install your headers, as your code and users' code will use the headers exactly the same way.
If in addition you have private headers, use the same structure, but in another hierarchy, for instance:
src/io/parser.hh
You may, or may not, decide to use src/foo
. The advantage of not using src/foo
is that it is easier to see what are public and private headers.
But never use relative paths.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With