Home > Software design >  Writing the header file of my own library
Writing the header file of my own library

Time:12-05

I write some functions to use dinamic arrays in c, without the problem of pointers ecc. , and now that i write enough code to use it properly, i want to encapsulate all this functions in a library.

Anyway in many of this function i use memcpy() method of the string.h.

So my question is:

  • Need i to include string.h in the .h file?

  • if i use string.h in the application where i will include my own library, will it be compilated two times?

  • is there a way to optimising the compilation?

There aren't some guides about it online, and if there are, they are so ambiguos and confusing.

I found something about the ifdef but i don't really understand how and why use it.

Can somebody give me an example of the header file with a similar scenario, or at least a tutorial for writing header files?

This is the first time that i try to write a library in c, so all tips will be appreciate.

CodePudding user response:

Your header file will be shared between the final application and your library. Therefore, the best place to include <string.h> is your header file.

Do not worry about system or standard headers being included more than once. They normally have protective #ifdefs which take care of including the code only once.

As a good practice you can also insert a custom #ifdef in your header. For instance, your header file would look like this:

/* Beginning of header file */
#ifndef ALEX_XXX_HEADER

#define ALEX_XXX_HEADER

/* Your header constants, prototypes, etc. here */

#endif
/* End of header file */

In this way, the compiler will first check whether _ALEX_XXX_HEADER has been defined. If it hasn't, it means it is the first time it hits this file. Then, it defines your header macro _ALEX_XXX_HEADER and processes all the code in the header.

If the header is included more than once, the next time the compiler finds the #ifndef line, it will skip the entire #ifndef clause. In other words, it will skip the entire header file. As a result, the header code will be included once only.

  • Related