Search code examples
cheader-files

How to organize header files in a library


Say I am writing a small libary in C, with most of the source code in two folders src/A and src/B, and where the header file src/A/a.h needs to include src/B/b.h. When writing code for a non-library project, I usually write

#include "B/b.h"

in a.h and use the -Isrc flag to tell the compiler where to look for header files.

Now suppose that my library is installed locally at ~/mylib and that I want to use functions from a.h from a different project. Simply including that file using

#include "~/mylib/src/A/a.h"

would not work, because ~/mylib/src/B/b.h might not be part in the search path. My question is about the canonical way to solve this issue. It's probably quite basic, but I haven't done any advanced programming in C and have been unsuccessful in my attemps to find a solution online.

Possible solutions I thought of are the following:

  • Add ~/mylib to the search path, but that might lead to problems if the library and client projects have header files with the same name (say src/helpers.h). Is it possible to include one header file without cluttering the search space with files I won't need?

  • Use relative paths in the library header files, but that doesn't feel very robust.

Thank you.


Solution

  • The normal approach is to have a separate directory specifically for the headers which form the public interface of your library. Usually this directory would be called 'include'.

    You would then place the public headers for your library under a library-specific directory in there, i.e. "mylib/include/mylib/b.h". This extra 'mylib' directory prevents clashes if you're using some other library that also has a "b.h". You can also, if you wish, keep other private headers, which do not form the public interface of your library, under the 'src' directory instead, to stop them being exposed to users of the library.

    This means a user of the library can then use "-I mylib/include" to include this directory, and include the individual files with, for example, "#include "mylib/b.h".