'Connecting your own header file in C

Project structure: enter image description here

When starting the makefile, I get an error: src/main.c:1:10: fatal error:

lib/hello.h: No such file or directory
    1 | #include <lib/hello.h>
      |          ^~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:10: main.o] Error 1

Makefile:

CFLAGS= -Wall -Wextra -Werror
CPPFLAGS = -I lib

all: hello

hello: main.o libhello.a
    $(CC) $(CFLAGS) $(CPPFLAGS) main.o hello.o -o hello

main.o: src/main.c
    $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $^

libhello.a: hello.o
    ar rcs $@ $^

hello.o: lib/hello.c
    $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $^

clean:
    rm -rf *.o hello

main.c:

#include <lib/hello.h>

int main(void)
{
    printHello();

    return 0;
}

hello.h

#pragma once
#include <stdio.h>
        
void printHello(void);

hello.c

#include <lib/hello.h>

void printHello(void)
{
    printf("Hello World!\n");
}

How to properly connect your header file using <>? Using relative paths through "" is not allowed.



Solution 1:[1]

Try -I . instead of -I lib in your makefile. The lib is already written in the source files, i.e. #include <lib/hello.h>.

$ tree
.
??? Makefile
??? lib
?   ??? hello.c
?   ??? hello.h
??? src
    ??? main.c

2 directories, 4 files
$ make
cc -c -Wall -Wextra -Werror -I . -o main.o src/main.c
cc -c -Wall -Wextra -Werror -I . -o hello.o lib/hello.c
ar rcs libhello.a hello.o
cc -Wall -Wextra -Werror -I . main.o hello.o -o hello
$ tree
.
??? Makefile
??? hello
??? hello.o
??? lib
?   ??? hello.c
?   ??? hello.h
??? libhello.a
??? main.o
??? src
    ??? main.c

2 directories, 8 files
$ ./hello
Hello World!
$ 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1