How to structure #includes in C

后端 未结 6 935
眼角桃花
眼角桃花 2020-12-06 07:48

Say I have a C program which is broken to a set of *.c and *.h files. If code from one file uses functions from another file, where should I include the header file? Inside

6条回答
  •  清歌不尽
    2020-12-06 08:20

    The .h file should define the public interface (aka the api) to the functions in the .c file.

    If the interface of file1 uses the interface of file2 then #include file2.h in file1.h

    If the implementation in file1.c makes use of stuff in file2.c then file1.c should #include file2.h.

    I must admit though that - because I always #include file1.h in file1.c - I normally wouldn't bother #including file2.h directly in file1.c if it was already #included in file1.h

    If you ever find yourself in the situation where two .c files #include each others .h files then it is a sign that modularity has broken down and you ought to think about restructuring things a bit.

提交回复
热议问题