4

Going over our course material, I noticed that when we #include standard libraries (for example #include <stdio.h>), these #includes appear in the .c file and not in the header file. The #includes that appear in the header file are those that are for local header files, #include "anotherheader.h".

Why is that? It'd make more sense to me that all #include declarations will appear in the header file, and all the .c files will derive them from there.

1
  • 1
    This is a matter of best practice and convention (which can differ between companies/people). Either way will work if done correctly. But one best practice is to put the #include in the file it is needed. So if a header references something from a library it should be the one to do the include. If the C file (directly) references something in a library then it should do the include. Commented Jan 21, 2017 at 21:56

2 Answers 2

3

Whether sources files include standard headers directly or via other included files is a matter of local coding conventions.

It is considered good style to follow these conventions:

  • include only the necessary headers ;
  • include standard headers before any other include files and local declarations ;
  • make every source file compilable as a separate entity, including project header files. This means you should include the standard headers needed for the types used in local header files at the top of these.
  • protect the definitions in a header file with a header guard: #ifndef SOME_SYMBOL / #endif.
Sign up to request clarification or add additional context in comments.

2 Comments

Consider an exception to "include standard headers before any other": In foo.c, the first is #include "foo.h". This insures "foo.h" compiles without prior #include ... requirements -unless there are in "foo.h". In others like bar.c, #include "foo.h" occurs as you suggest.
In addition, it is also considered good practice to put all includes in the header file, since the header is the public interface. That way, the user can quickly find all file dependencies.
2

It is good practice to include only what is really necessary in the header file to avoid circular dependencies and to allow for shorter build times.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.