Home > Software design >  How give subdirectories for C project to include .h file in makefile?
How give subdirectories for C project to include .h file in makefile?

Time:11-04

I have C project which is divided in Z modules. Each module has its own subfolder which has /inc/ for header files and /src/ for src files. Like shown in image:

enter image description here

Zth_Module.c has include files from various other modules:

/*In Zth_Module.c*/
#include "first.h"
#include "second.h"
#include "third.h"

If in makefile -I is used, how can path for each subdirectory can be given? It is showing fatal error: Timer.h: No such file or directory for include file first.h or second.h which are in other subdirectories.

What is the way to provide path to search all *.h files?

CodePudding user response:

Some approaches to handling this are:

  • In the makefile, include a -I directory switch in the compilation flags for each directory containing a header file that might be included. The -I switch tells the compiler to search the following directory, in addition to the directories it usually searches. For example, you would add switches -I first/inc -I second/inc -I third/inc to the compilation flags. You can list the directories manually in the makefile or use GNU Make features for discovering them during the make.
  • Add a single -I directory switch listing a root directory for the project to the compilation switches and change all the #include directives in source code to use paths relative to that root, such as #include "first/inc/first.h".
  • Create a makefile target that copies all header files to a single common directory, add one -I directory switch for that directory to the compilation switches, and list that target as a dependency for each of the object files, so that make always executes the commands for that target before compiling a source file. That target could be named for the directory used to gather the header files, and it would often be in a temporary or staging area for the build. Also, if you have a clean target, one of its actions could be to remove that directory.
  • Related