0

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.

12iq
  • 83
  • 5
  • "Using relative paths through "" is not allowed." So what is `#include ` then? – Yunnosch May 14 '22 at 10:09
  • *Using relative paths through "" is not allowed.* Ehh? `#include "lib/hello.h"` should be fine? – Andrew May 14 '22 at 10:20
  • See also https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename – Andrew May 14 '22 at 10:21
  • You can use three consecutive back-ticks before and after your monospaced text to visualize the tree structure instead of using a picture. – Franck May 14 '22 at 10:24

1 Answers1

0

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!
$ 
Franck
  • 1,340
  • 2
  • 3
  • 15