Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ #include formatting best practice

Tags:

c++

c

include

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.

  1. include "mycode.h" // no knowledge of path, assumes structure that I described

  2. include "../../project_name/inc/mycode.h" // seems a bit convoluted, but shows the file structure better

Are there any other options that I'm missing?

like image 847
It'sPete Avatar asked Jun 12 '13 07:06

It'sPete


1 Answers

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.

like image 139
akim Avatar answered Sep 30 '22 08:09

akim