K.Mulier K.Mulier - 1 month ago 13
C Question

GNU gcc compiler cannot handle partial include statements

Imagine that I have a C-project in the following folder:

C:\microcontroller\stm32\myProject


I have two important folders inside myProject:

- source
=> here are all my
.c
and
.h
files

- build
=> gcc will write all the object files in here

Note: as you can see, the backward slashes indicate that this is happening on a Windows pc.

The figure below gives an overview:

enter image description here

I will not display my complete makefile here, because that would lead us too far. The rules inside the makefile for all
.c
=>
.o
files are similar. Let us just focus on the compilation of one specific file:
fileA2.c
:

--------------------- COMPILATION OF FILE fileA2.c -------------------

Building ./build/folderA/fileA2.o

arm-none-eabi-gcc C:\\microcontroller\\stm32\\myProject\\source\\folderA\\fileA2.c
-o C:\\microcontroller\\stm32\\myProject\\build\\folderA\\fileA2.o
-c
-MMD
-mcpu=cortex-m7
-...
-IC:/microcontroller/stm32/myProject/source/folderA
-IC:/microcontroller/stm32/myProject/source/folderB


Notice that the gcc call ends with two include flags: one for folderA and one for folderB. This enables gcc to use any of the header files from these folders (
fileA1.h
,
fileA2.h
or
fileB1.h
) if
fileA2.c
has an import statement.

Let us now consider the source code in
fileA2.c
. We assume that this file needs to include
fileA2.h
and also
fileB1.h
.

/*******************************/
/* SOURCE CODE fileA2.c */
/*******************************/

// Some include statements
#include "fileA2.h"
#include "fileB1.h"

// Code
...


These include statements work perfectly. The gcc compiler retrieves the files
fileA2.h
and
fileB1.h
in the given folders. But I noticed that the following does not work:

/*******************************/
/* SOURCE CODE fileA2.c */
/*******************************/

// Some include statements
#include "fileA2.h"
#include "folderB/fileB1.h"

// Code
...


The last include statement is a 'partial path' to the file. I get the error when compiling:

fatal error: folderB/fileB1.h: No such file or directory


How can I get gcc to handle this?

PS: It is not my own habit to use 'partial paths'. But they appear a lot in the libraries from the silicon vendor of my chip, so I have to live with it.

jxh jxh
Answer

You specify two paths to look for includes other than the current directory for the source file:

           -IC:/microcontroller/stm32/myProject/source/folderA
           -IC:/microcontroller/stm32/myProject/source/folderB

You get the error because neither
C:/microcontroller/stm32/myProject/source/folderA/folderB/fileB1.h nor
C:/microcontroller/stm32/myProject/source/folderB/folderB/fileB1.h exists.

To address the error, you can add the following path:

           -IC:/microcontroller/stm32/myProject/source