I've been learning c++ and encountered the following question: I have a directory structure like:
- current directory
- Makefile
- include
- header.h
- src
- main.cpp
my header.h :
#include <iostream>
using namespace std;
void print_hello();
my main.cpp:
#include "header.h"
int main(int argc, char const *argv[])
{
print_hello();
return 0;
}
void print_hello()
{
cout<<"hello world"<<endl;
}
my Makefile:
CC = g++
OBJ = main.o
HEADER = include/header.h
CFLAGS = -c -Wall
hello: $(OBJ)
$(CC) $(OBJ) -o $@
main.o: src/main.cpp $(HEADER)
$(CC) $(CFLAGS) $< -o $@
clean:
rm -rf *o hello
And the output of make is:
g++ -c -Wall src/main.cpp -o main.o src/main.cpp:1:20: fatal error: header.h: No such file or directory compilation terminated. Makefile:10: recipe for target 'main.o' failed make: *** [main.o] Error 1
What mistakes I have made in here. It's frustrating. Really appreciate any advice!
You told the Makefile that include/header.h
must be present, and you told the C++ source file that it needs header.h
… but you did not tell the compiler where such headers live (i.e. in the "include" directory).
Do this:
CFLAGS = -c -Wall -Iinclude
You can either add a -I
option to the command line to tell the compiler to look there for header files. If you have header files in include/
directory, then this command should work for you.
gcc -Iinclude/
Since, you are using makefile
, you can include this option in CFLAGS
macro in your makefile.
CFLAGS = -Iinclude/ -c -Wall
OR
You can include header files using #include "../include/header.h"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With