简体   繁体   中英

Find all header files in all sub-directories

I am trying to use any header from my include folder in any source file in my src folder. Right now, I am doing "#include ../../include/subfolder/file.h" or #include "../include/otherfile.h" to get access to my header files, but this is very verbose, and anytime I do a directory restructure, I have to go back and change every reference to the affected header files. I would like to just be able to do #include "file.h" from any source file, but I can't seem to do it. Doing -Iinclude or -Iinclude/ can't find the headers in subfolder for some reason. Changing my include statement to #include <file.h> also doesn't work. What can I do to fix this?

I have a project layout that looks like this:

Makefile

include
    subfolder
        file.h
    otherfile.h

src
    subfolder
        file.c
    otherfile.c

My Makefile looks like this:

TARGET = program
LIBS = -llibs
CC = gcc
CFLAGS = -Wall -g -Iinclude/

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.c, %.o, $(shell find . -name '*.c'))
HEADERS = $(shell find . -name '*.h')

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $@

clean:
    find . -type f -name '*.o' -exec rm {} +
    find . -type f -name $(TARGET) -exec rm {} +

Simple, just use

#include <myheader.h>

and pass the relevant directory to the compiler through the -I switch.

For instance, if myheader.h was in include/subfolder then,

$(CC) -Iinclude/subfolder

will work.

Note that you must also include the subfolder in the -I argument because only the top level directory is scanned for headers.

You can auto-generate the include dir flags simply enough:

 INC_DIRS := $(shell find include -type d)
 C_INC_FLAGS := $(addprefix -I,$(INC_DIRS))

 %.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) $(C_INC_FLAGS) -c $< -o $@

Note, that most systems have a maximum line length (usually around 64k), so if you have LOTS of directories, you may have to worry that you exceed the max line length (at which point you pipe the dirs to a file and include with @file ...)

Also, this doesn't work if you autogenerate new directories in your include directory through your make rules, as those directories will not be there when you populate INC_DIRS the first time around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM