Home > OS >  How to do all includes in source file?
How to do all includes in source file?

Time:10-27

Is it possible to write all includes in the source file?

Let's say we have to write a module called sum (sum.h/sum.c) that provides sum functions for all numeric types.

All function declarations are done in sum.h file as follows:

uint16_t sum(uint16_t a, uint16_t b); // uint16 sum function

in this case I have to include <stdint.h> in sum.h.

Is it possible, for any version of the C standard, to do this include in the source file sum.c?

CodePudding user response:

Is it possible, for any version of the c standard, to do this include in the source file sum.c .

It is possible in all versions of the C standard to include the standard header in the source file. In fact, doing so it's arguably recommended.

However, if you were asking if you could avoid including the header in sum.h while still relying on the typedef, no there's no C standard version where that's possible.

CodePudding user response:

Either is fine as far as the C standard goes, as long as each inclusion is done before a feature from the included header is used.

Apart from that, there are two schools of coding style:

  • Either include all headers used by a module from the .h file, in order to document that modules file dependencies to the user.

    Generally it's a good thing to tell the user of your code which headers that are required for the program to build. There's few things more frustrating than including some 3rd party lib in your code, then get "mysterious linker error: 1" and from there you have no idea why - at best the problem points somewhere inside the included lib.

    Also, the header file itself might require access to various types or constants in the included files.

  • Or alternatively include all headers used from the .c file, to hide the file dependencies.

    There are scenarios when you are making a library and you only wish the user to interact with a single header file, hiding the internal file structure of the lib away from them, similar to private encapsulation. You might not want to expose information about which private headers your code are using to the caller - particularly if you are linking your code into a single lib binary (or DLL etc).

Which of these styles to use is fairly subjective and as indicated above, you might use one style over the other depending on the requirements of the specific project.

  • Related