Rastapopoulos
Rastapopoulos

Reputation: 507

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:

Thank you.

Upvotes: 4

Views: 2463

Answers (2)

Sean Burton
Sean Burton

Reputation: 960

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".

Upvotes: 7

NastyDiaper
NastyDiaper

Reputation: 2558

Why aren't you using the standard implementation? Break out into header and source files into their own directories. Add #define headers to avoid multiple includes or namespace corruption.

Here is your directory structure:

~/mylib/headers/a.h
                b.h
~/mylib/src/a.c
            b.c

Now a.h will have at the very top of the file...

#ifndef __A_H__
#define __A_H__
    //  code

#include "~/mylib/headers/b.h"

    // end of file
#endif

Now b.h will have at the very top of the file...

#ifndef __B_H__
#define __B_H__
    //  code

    // end of file
#endif

Then just compile. gcc -I~/mylib/headers

If you have 2 helpers.h just change the #define __HELPERS_H__ in one of the files to something else like #define __HELPERS2_H__

Upvotes: 2

Related Questions